定时任务:在开发过程中是经常能够使用到的:定时发布邮件等等
先了解一下什么时cron表达式?
它是定义执行任务时间的一种时间表达式,使用方法
@Scheduled(cron = "0/2 * * * * ? "),这里代码的含义是每两秒执行以下此方法
总共有六个数据,它对应的则是cron表达式:秒 分 时 日 月 周还有一个数据可写可不写就是年
cron表达式并非一定要了解,每个数据可以通过生成器得到自己需要的数据
cron表达式生成器这个网站可以帮助我们获取定时任务的时间信息
创建一个ScheduledService类:定时执行此类下面的方法
代码:
package com.example.demo.service;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service //交给spring容器进行管理
public class ScheduledService {
//实现的功能是每两秒执行方法:定时执行任务
//cron表达式:秒 分 时 日 月 周
@Scheduled(cron = "0/2 * * * * ? ")
public void Show(){
System.out.println("输出");
}
}
注解:@Scheduled:设计执行任务的时间配置信息
注意:这里的时间单位都是毫秒
@Scheduled(fixedDelay = 1000)
上一个任务结束到下一个任务开始的时间间隔为固定的1秒,任务的执行总是要先等到上一个任务的执行结束@Scheduled(fixedRate = 1000)
每间隔1秒钟就会执行任务(如果任务执行的时间超过1秒,则下一个任务在上一个任务结束之后立即执行)@Scheduled(fixedDelay = 1000, initialDelay = 2000)
第一次执行的任务将会延迟2秒钟后才会启动@Scheduled(cron = “0 15 10 15 * ?”)
Cron表达式,每个月的15号上午10点15分开始执行任务在配置文件中配置任务调度的参数
开启定时任务
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling //开启定时任务功能
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
运行项目:
看测试结果每隔两秒显示一个'输出'