使用方法
操作非常簡單,只要按如下幾個步驟配置即可
1. 導入jar包或添加依賴,其實定時任務只需要spring-context即可,當然起服務還需要spring-web;
2. 編寫定時任務類和方法,在方法上加@Scheduled注解,注意定時方法不能有返回值;
3. 在spring容器中注冊定時任務類;
4. 在spring配置文件中開啟定時功能。
示例Demo
maven依賴
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.6.RELEASE</version> </dependency>
定時任務類
@Component(value = "scheduleJob") public class ScheduleJob { /** * 固定間隔時間執行任務,單位為微秒 */ @Scheduled(fixedDelay = 2000) public void timeJob() { System.out.println("2s過去了......"); } /** * 使用cron表達式設置執行時間 */ @Scheduled(cron = "*/5 * * * * ?") public void cronJob() { System.out.println("cron表達式設置執行時間"); } }
spring配置文件——注冊定時任務類,單個注冊或包掃描均可,這里使用包掃描,這時定時任務類必須加組件注解
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--掃描指定包下加了組件注解的bean--> <context:component-scan base-package="cn.monolog.diana.schedule" /> </beans>
spring配置文件——開啟定時功能
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd"> <!--開啟定時功能--> <task:executor id="executor" pool-size="10" queue-capacity="128" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven executor="executor" scheduler="scheduler" /> </beans>
啟動服務后,控制台會輸出如下語句
2s過去了......
2s過去了......
cron表達式設置執行時間
2s過去了......
2s過去了......
2s過去了......
cron表達式設置執行時間
2s過去了......
2s過去了......
指定定時任務執行時間的方式
從上面的demo可以看出,定時任務的執行時間主要有兩種設置方式:
1. 使用@Scheduled注解的fixedDelay屬性,只能指定固定間隔時長;
2. 使用@Scheduled注解的cron屬性,可以指定更豐富的定時方式。
那么問題來了,這個cron表達式該怎么寫?