SpringBoot中使用@Scheduled注解创建定时任务的实现
在项目日常开发过程中,经常需要定时任务来帮我们做一些工作,如清理日志。定时任务的实现方法主要有Timer、Quartz以及elastic-job
Timer实现定时任务
只执行一次的定时任务
Timertimer=newTimer(); timer.schedule(newTimerTask(){ @Override publicvoidrun(){ System.out.println("2000毫米后执行一次。"); } },2000); timer.schedule(newTimerTask(){ @Override publicvoidrun(){ System.out.println("5000毫米后执行一次。"); } },newDate(System.currentTimeMillis()+5000));
循环执行任务
Timertimer=newTimer(); timer.schedule(newTimerTask(){ @Override publicvoidrun(){ System.out.println(111); } },1000,2000);//1000毫米后执行第一次,之后每2000毫米执行一次
终止任务
timer.concel();
Timer是JDK实现的定时任务,用起来简单、方便,对一些简单的定时任务可以使用它。由于它不支持cron表达式,现在已经很少用了。
Quartz实现定时任务
Quartz是一个完全由Java编写的开源作业调度框架,可以用它来实现定时任务。
在pom.xml文件添加Quartz依赖
org.quartz-scheduler quartz 2.2.1 org.quartz-scheduler quartz-jobs 2.2.1 org.slf4j slf4j-api 1.7.25 org.slf4j slf4j-simple 1.7.6
编写Job
定时执行的任务
publicclassQuartzJobimplementsJob{ publicvoidexecute(JobExecutionContextcontext)throwsJobExecutionException{ JobDataMapjobDataMap=context.getJobDetail().getJobDataMap(); Stringhello=(String)jobDataMap.get("hello"); System.err.println(hello); } }
编写Task
publicvoidtask(){ //该map可在job中获取 JobDataMapmap=newJobDataMap(); map.put("hello","world"); JobDetailjobDetail=newJob(QuartzJob.class). withIdentity("myJob","myGroup"). setJobData(map).build(); /* *简单定时器 * *执行时间间隔 *withIntervalInMilliSeconds毫秒 *withIntervalInSeconds秒 *withIntervalInMinutes分钟 *withIntervalInHours小时 * *执行次数 *repeatForever重复执行 *withRepeatCount次数 */ SimpleScheduleBuilderscheduleBuilder=simpleSchedule().withIntervalInSeconds(3).withRepeatCount(10); /* *corn定时器 * *corn表达式,使用更灵活 *corn表达式在线生成http://cron.qqe2.com/ */ CronScheduleBuildercronScheduleBuilder=CronScheduleBuilder.cronSchedule("0001*?"); Triggertrigger=newTrigger().startAt(newDate()).//startNow()默认现在开始 withIdentity("myTrigger","myGroup"). //withSchedule(scheduleBuilder).build(); withSchedule(cronScheduleBuilder).build(); try{ //1.创建Scheduler工厂 SchedulerFactoryschedulerFactory=newStdSchedulerFactory(); //2.获取实例 Schedulerscheduler=schedulerFactory.getScheduler(); //3.设置jobDetail详情和trigger触发器 scheduler.scheduleJob(jobDetail,trigger); //4.定时任务开始 scheduler.start(); }catch(SchedulerExceptione){ e.printStackTrace(); } }
在项目启动的时候调用task方法即可启动定时任务。
SpringBoot创建定时任务
SpringBoot默认已经实现了定时任务,只需要添加相应的注解即可完成
pom.xml文件配置
pom.xml不需要添加其他依赖,只需要加入SpringBoot依赖即可,这里我们添加一个web和test的依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-devtools true
在启动类上面加上@EnableScheduling注解
在启动类上面加上@EnableScheduling注解即可开启定时任务
@EnableScheduling @SpringBootApplication publicclassSchedulingApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(SchedulingApplication.class,args); } }
编写定时任务
@Component publicclassScheduledTask{ @Scheduled(initialDelay=1000,fixedDelay=1000) publicvoidtask1(){ System.out.println("延迟1000毫秒后执行,任务执行完1000毫秒之后执行!"); try{ Thread.sleep(2000); }catch(InterruptedExceptione){ e.printStackTrace(); } } @Scheduled(fixedRate=2000) publicvoidtask2(){ System.out.println("延迟1000毫秒后执行,之后每2000毫秒执行一次!"); } }
除了这些还支持cron表达式
@Scheduled(cron="*/2****?") publicvoidtask3(){ System.out.println("每2秒执行一次!"); }
启动SpringBoot项目在控制台就会看到任务定时执行
cron表达式
以下是cron表达式的的两种语法
SecondsMinutesHoursDayofMonthMonthDayofWeekYear SecondsMinutesHoursDayofMonthMonthDayofWeek
每一个域可出现的字符如下:
- Seconds:可出现",-*/"四个字符,有效范围为0-59的整数
- Minutes:可出现",-*/"四个字符,有效范围为0-59的整数
- Hours:可出现",-*/"四个字符,有效范围为0-23的整数
- DayofMonth:可出现",-*/?LWC"八个字符,有效范围为0-31的整数
- Month:可出现",-*/"四个字符,有效范围为1-12的整数或JAN-DEc
- DayofWeek:可出现",-*/?LC#"四个字符,有效范围为1-7的整数或SUN-SAT两个范围。1表示星期天,2表示星期一,依次类推
- Year:可出现",-*/"四个字符,有效范围为1970-2099年
举几个例子
*/2****?表示每2秒执行一次! 0021*?*表示在每月的1日的凌晨2点调度任务 01510?*MON-FRI表示周一到周五每天上午10:15执行作业 01510?6L2002-2006表示2002-2006年的每个月的最后一个星期五上午10:15执行作
推荐一个cron表达式在线生成工具
http://tools.jb51.net/code/Quartz_Cron_create
参考资料
本文所有代码放在Github上
到此这篇关于SpringBoot中使用@Scheduled注解创建定时任务的实现的文章就介绍到这了,更多相关SpringBoot创建定时任务内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!