quartz 简单使用

依赖添加

 <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.3.0</version>
        </dependency>

定时执行任务类

public class PrintWordsJob implements Job {

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		String printTime = new SimpleDateFormat("yy-MM-dd HH-mm-ss").format(new Date());
		System.out.println("PrintWordsJob start at:" + printTime + ", prints: Hello Job-" + new Random().nextInt(100));

	}
}

定义定时任务的触发器与调度器

public class MyScheduler {

	public static void main(String[] args) throws SchedulerException, InterruptedException {
		// 1、创建调度器Scheduler
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		Scheduler scheduler = schedulerFactory.getScheduler();
		// 2、创建JobDetail实例,并与PrintWordsJob类绑定(Job执行内容)
		JobDetail jobDetail = JobBuilder.newJob(PrintWordsJob.class)
										.withIdentity("job1", "group1").build();
		// 3、构建Trigger实例,每隔1s执行一次
		Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
										.startNow()//立即生效
										.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(1).repeatForever())
//										.startAt(startDate) //开始启动的时间
//										.endAt(endDate) //结束的时间
//										.withSchedule(CronScheduleBuilder.cronSchedule("* 30 10 ? * 1/5 2018")) //可配置 cron 表达式
										.build();//一直执行

		//4、执行
		scheduler.scheduleJob(jobDetail, trigger);
		System.out.println("--------scheduler start ! ------------");
		scheduler.start();
		System.out.println("--------scheduler shutdown ! ------------");
	}
}

remark: 可定义定时任务的启动时间,结束时间

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/118709060

相关文章