您的位置:首页 > 编程语言 > Java开发

Spring Boot 配置定时任务

2017-12-14 23:35 471 查看
package com.zooper.demo;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

/**
* 每隔5秒执行一次
*/
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}

/**
* 根据cron表达式格式触发定时任务
*  cron表达式格式:
*      1.Seconds Minutes Hours DayofMonth Month DayofWeek Year
*      2.Seconds Minutes Hours DayofMonth Month DayofWeek
*  顺序:
*      秒(0~59)
*      分钟(0~59)
*      小时(0~23)
*      天(月)(0~31,但是你需要考虑你月的天数)
*      月(0~11)
*      天(星期)(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
*      年份(1970-2099)
*
*  注:其中每个元素可以是一个值(如6),一个连续区间(9-12),一个间隔时间(8-18/4)(/表示每隔4小时),一个列表(1,3,5),通配符。
*  由于"月份中的日期"和"星期中的日期"这两个元素互斥的,必须要对其中一个设置?.
*/
@Scheduled(cron="5 * * * * ?")
public void cronScheduled() {
log.info("cron : The time is now {}", dateFormat.format(new Date()));
}
}


启用定时任务

package com.zooper.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {

public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: