項目框架: SpringMVC、MyBatis、JSP
1. 首先配置spring.xml文件
<?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" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd"> <!-- 注解定時任務 --> <task:annotation-driven/>
2. 配置定時任務類
@Component public class MessageSendService { /** * 記錄日志類 */ public Log logger = LogFactory.getLog(this.getClass()); /** * 定時任務方法 */ @Scheduled(cron = "0/10 * * * * ? ") public void send(){ logger.info("start....."); } }
@Component 注解是讓Spring可以掃描到並初始化,第一步的配置就是做這個用的
@Scheduled 注解是配置定時任務的執行時間,上面的配置是讓定時任務每10執行一次send()方法
3. 實際的項目中定時任務的執行時間可能要在配置文件中配置,就需要用到另一個注解 @PropertySource
@Component @PropertySource(value="classpath:application.properties") public class MessageSendService { /** * 記錄日志類 */ public Log logger = LogFactory.getLog(this.getClass()); /** * 方法 */ @Scheduled(cron = "${jobs.message}") public void send(){ logger.info("start....."); } }
@PropertySource 指定配置文件的位置,和配置文件的名稱
@Scheduled 注解做相應的修改
4. application.properties 文件配置
## 輪詢時間配置
jobs.message=0/10 * * * * ?
這個定時任務時間配置和linux的crontab差不多
5. Scheduled 參數1
@Scheduled(fixedDelay = 5000) public void doSomething() { // something that should execute periodically }
這個方法將以一個固定延遲時間5秒鍾調用一次執行,這個周期是以上一個調用任務的完成時間為基准,在上一個任務完成之后,5s后再次執行
當方法執行超過5秒,下一個輪詢發現有正在執行的方法,直接跳過
6. Scheduled 參數2
@Scheduled(fixedRate = 5000) public void doSomething() { // something that should execute periodically }
這個方法將以一個固定速率5s來調用一次執行,這個周期是以上一個任務開始時間為基准,從上一任務開始執行后5s再次調用
當方法執行時間超過5秒,下一個輪詢會阻塞,上一個任務執行完成,立即執行此次輪詢方法