package com.boot.web.springBoot;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Description:
*
* @author :zhhe
* @version : 1.0.0
* @time : 18:50 2018/7/2
*/
public class MyJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date nowTime = new Date();
System.err.println("开始执行调度任务====现在时间是:" + sdf.format(nowTime) +
"---jonKey=" + jobExecutionContext.getJobDetail().getKey());
}
public static void taskScheduler(String jobName, String jobGroup, Date runTime) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.err.println("调用taskScheduler方法,新增调度任务=====jobName:"+jobName+" runTime:"+sdf.format(runTime));
//构建Job
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(jobName, jobGroup).build();
//构建Trigger
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger", jobGroup)
.startAt(runTime).build();
//创建调度者工厂 绑定Job和Trigger
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
//创建一个调度者
Scheduler scheduler = schedulerFactory.getScheduler();
//注册并进行调度
scheduler.scheduleJob(job, trigger);
//启动调度
scheduler.start();
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 5; i++) {
Date runTime = new Date();
//1分钟
long time = 60 * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
//1分钟后的时间
Date afterDate = new Date(now.getTime() + time);
System.err.println("预计开始执行时间:"+sdf.format(afterDate));
taskScheduler("job00" + (i + 1), "jobGroup00" + (i + 1), afterDate);
Thread.sleep(5000);
}
}
}
Quartz任务调度实例
最新推荐文章于 2023-02-01 14:53:05 发布