springboot定时任务

springboot定时任务参考:http://spring.io/guides/gs/scheduling-tasks/

创建一个springboot定时任务非常容易,2步完成:
1)在启动类(Application)中增加@EnableScheduling;
2)定时任务方法增加@Scheduled。

示例:

package com.coding.springboot.demo.task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by j.tommy on 2015/11/2.
 * springboot定时任务,参考:http://spring.io/guides/gs/scheduling-tasks/
 */
@Component
public class TaskDemo1 {
    public static final Logger LOGGER = LoggerFactory.getLogger(TaskDemo1.class);
    public static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @Scheduled(fixedRate = 5000)
    public void task() throws Exception {
        LOGGER.info("现在时间是:" + DATE_FORMAT.format(new Date()));
        // 这里抛出一个异常,测试发现任务并不会终止。并不会影响下一次任务的执行
        throw new Exception();
        //        int i = 1/0;
    }
    @Scheduled(cron = "0/5 * * * * ?")
    public void task2() {
    LOGGER.info("task2 executed." + DATE_FORMAT.format(new Date()));
    }
}

你可能感兴趣的:(springboot系列)