由于有一天是没有更新博客,导致在博客的书写日期上面是一直晚一天的。
今天主要实战的一些知识储备罗列--计划任务ScheduledTask
今天的定时任务是昨天的Spring aop应用的实际应用,废话不多说,上代码:
1,创建配置类,启动注解的支持
package com.amarsoft.springboot.taskscheduler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan("com.amarsoft.springboot.taskscheduler")
@EnableScheduling
public class TaskScheduledConfig {
}
2,创建计划任务执行类
package com.amarsoft.springboot.taskscheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate=5000)
public void reportCurrentTime(){
System.out.println("每个五秒执行一次"+dateFormat.format(new Date()));
}
@Scheduled(cron="0 29 0 ? * *" )
public void fixTime(){
System.out.println("在指定的时间内"+dateFormat.format(new Date())+"执行任务");
}
}
代码解释:>1.通过@Scheduled声明该方法是计划任务,使用fixedRate属性每个固定时间执行,单位是毫秒
>2.使用cron属性可按照指定时间执行,此处是写的每天的00:29:00执行,cron是unix和类unix系统下的定时任务
注意cron的配置: cron是设置定时执行的表达式
@Scheduled(cron="0 29 0 ? * *" )表示每天的00:29:00执行一次
@Scheduled(cron="0 0/5 * * * ?" )表示每隔五分钟执行一次
zone表示执行时间的时区
FixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行
fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行
initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间
3,测试运行
package com.amarsoft.springboot.taskscheduler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TaskScheduledApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(TaskScheduledConfig.class);
}
}
4,执行结果: