Browse Source

cron方式

master
燕鹏 4 years ago
parent
commit
8199c6fe6e
  1. 30
      src/main/java/com/aiprose/sbquartz/quartz/CronJob.java
  2. 37
      src/main/java/com/aiprose/sbquartz/quartz/CronScheduler.java
  3. 2
      src/main/java/com/aiprose/sbquartz/quartz/DemoScheduler.java

30
src/main/java/com/aiprose/sbquartz/quartz/CronJob.java

@ -0,0 +1,30 @@
package com.aiprose.sbquartz.quartz;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @author yanpeng
* @version 1.0
* @desc 具体实现业务逻辑
* @company 北京中经网软件有限公司
* @date 2020/12/23 16:02
*/
//这两个是在分布式环境中使用的
//@PersistJobDataAfterExecution
//@DisallowConcurrentExecution
@Component
@Slf4j
public class CronJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobKey key = context.getJobDetail().getKey();
log.info("task name: {}",key.getName());
JobDataMap jobDataMap = context.getTrigger().getJobDataMap();
log.info("传递的参数:name:{}",jobDataMap.get("name"));
log.info("我要开始做具体的工作了,{}",new Date());
}
}

37
src/main/java/com/aiprose/sbquartz/quartz/CronScheduler.java

@ -0,0 +1,37 @@
package com.aiprose.sbquartz.quartz;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
/**
* @author yanpeng
* @version 1.0
* @desc TODO
* @company 北京中经网软件有限公司
* @date 2020/12/23 16:50
*/
@Component
@Slf4j
public class CronScheduler {
@Resource
private Scheduler scheduler;
@PostConstruct
public void init() throws SchedulerException {
startTaskJob();
scheduler.start();
}
private void startTaskJob() throws SchedulerException {
JobDetail jobDetail = JobBuilder.newJob(CronJob.class) .withIdentity("job1", "group1").build();
// 6的倍数秒执行 也就是 6 12 18 24 30 36 42 ....
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/6 * * * * ?");
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1")
.usingJobData("name","nelson").withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail,cronTrigger);
}
}

2
src/main/java/com/aiprose/sbquartz/quartz/DemoScheduler.java

@ -36,6 +36,8 @@ public class DemoScheduler {
Date nowTime = new Date();
nowTime.setTime(nowTime.getTime() + 5000l);
Trigger subsys = TriggerBuilder.newTrigger().withIdentity(uuid).startAt(nowTime).build();
//2分钟循环一次
//Trigger subsys = TriggerBuilder.newTrigger().withIdentity(uuid).startAt(nowTime).withSchedule(SimpleScheduleBuilder.repeatHourlyForever().withIntervalInSeconds(2)).build();
scheduler.scheduleJob(jobDetail, subsys);
}
}

Loading…
Cancel
Save