赞
踩
参考文章:https://blog.csdn.net/noaman_wgs/article/details/80984873
定时任务有这么几部分组成,专门写业务逻辑的地方(job);定时信息的设置(Trigge ); 调度器 Scheduler(将任务job与 触发器Trigge 结合 );
完整的demo 直接上代码吧:
- package com.quartz.task;
-
-
- import org.quartz.Job;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobExecutionException;
-
- /**
- * @ClassName TaskJob
- * @Description TODO
- * @Date 2019/10/17 10:22
- * @Version 1.0.0
- **/
- public class TaskJob implements Job {
- @Override
- public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
- System.out.println("任务执行中---------");
- }
- }
- package com.quartz.task;
-
-
- import org.quartz.*;
- import org.quartz.impl.StdSchedulerFactory;
-
- import java.util.Date;
- import java.util.concurrent.TimeUnit;
-
- /**
- * @ClassName MyScheduler
- * @Description TODO 该类是定时任务实现的实例 完全基于代码 ,而不是xml方式实现的
- * @Date 2019/10/17 10:23
- * @Version 1.0.0
- **/
- public class MyScheduler {
- public static void main(String[] args) throws SchedulerException, InterruptedException {
- //1 创建 scheduler 实例
- SchedulerFactory scheFactory =new StdSchedulerFactory();
- Scheduler scheduler = scheFactory.getScheduler();
- // 2 创建JobDeatil 实例
- JobDetail jobDetail = JobBuilder.newJob(TaskJob.class)
- .withIdentity("job1", "group1").build();
- // 3 创建Trigger实例 每隔一秒 执行一次
- // Trigger trigger = TriggerBuilder.newTrigger()
- // .withIdentity("trigger", "trigger")
- // .startNow()
- // .withSchedule(
- // SimpleScheduleBuilder.simpleSchedule()
- // .withIntervalInMilliseconds(1000)
- // .repeatForever()//一直执行
- // ).build();
- // 创建 CronTrigger
- Date startDate = new Date();
- startDate.setTime(startDate.getTime() + 5000);
- Date endDate = new Date();
- endDate.setTime(startDate.getTime() + 5000);
-
- Trigger trigger = TriggerBuilder.newTrigger()
- .withIdentity("trigger", "trigger")
- .usingJobData("job1", "这是jobDetail1的trigger")
- .startNow()//立即生效
- .startAt(startDate)
- .endAt(endDate)
- // cron 表达式
- .withSchedule(CronScheduleBuilder.cronSchedule("*/5 * * * * ?"))
- .build();
-
-
-
- // 4执行
- scheduler.scheduleJob(jobDetail,trigger);
- System.out.println("start 开始执行定时任务");
- scheduler.start();
- //睡眠
- TimeUnit.MINUTES.sleep(1);
- scheduler.shutdown();
- System.out.println("--------scheduler shutdown ! ------------");
-
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。