1.引入依赖
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.1</version>
</dependency>
2.创建任务内容
public class Lizhi implements Job {
@Autowired
IStaffBaseService iStaffBaseService;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
log.info("离职审批过的人:"+jobDataMap.get("staffBaseId"));
}
}
3.启动并创建定时任务
@Autowired
private Scheduler scheduler;
String jobName = "离职审批任务"+staffBase.getId();
String suerid = staffBase.getId();
String dodate = map.get("lizhi_date");
String date = "";
try {
date = FlowUtils.getCron(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dodate));
} catch (ParseException e) {
e.printStackTrace();
}
log.info("执行的时间为:"+date);
JobDetail jobDetail = JobBuilder.newJob(Lizhi.class).withIdentity(jobName).usingJobData("staffBaseId",suerid).build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity(jobName).withSchedule(CronScheduleBuilder.cronSchedule(date)).build();
//3、创建调度器Scheduler并执行
Scheduler scheduler = null;
try {
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.scheduleJob(jobDetail, trigger);
log.info("创建离职定时任务:["+suerid+"]ID:"+staffBase.getId());
scheduler.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
4.Flowutils
/**
* 获取指定时间的cron表达式
* @param date
* @return
*/
public static String getCron(Date date) {
String dateFormat = "ss mm HH dd MM ? yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
String formatTimeStr = null;
if (date != null) {
formatTimeStr = sdf.format(date);
}
return formatTimeStr;
}
- THE END -
最后修改:2023年5月4日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://www.95app.top/quartz-%e5%9f%ba%e6%9c%ac%e4%bd%bf%e7%94%a8sprignboot%e4%bd%bf%e7%94%a8quartz/