加载中...
加载中...
SpringBoot定时任务@Scheduled

SpringBoot定时任务@Scheduled 原创

定时任务是系统中比较普遍的一个功能,例如数据归档、清理、数据定时同步(非实时),定时收发,流量控制等等都需要用到定时任务。

Schedule写在core包当中,在SpringBoot中使用定时任务只需要简单配置。

1.首先在**Application启动类中加入@EnableScheduling注解开启定时任务。

@SpringBootApplication
//这里开启定时任务
@EnableScheduling
public class MyApplication {

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

2、编写具体的定时任务组件(@Component注解),并且在需要定时调度的方法上添加@Scheduled触发器。Spring实现了Quartz简单的和cron表达式两种触发方式,这里用cron表达式,”0/30 * * * * ?”表示每30秒触发一次。

package com.leixing.blog.conf;

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

import java.util.Date;

/**
* 定时任务
*/
@Component
public class MyTask {

private final Logger logger = LoggerFactory.getLogger(getClass());

/**
* 固定cron配置定时任务
*/
@Scheduled(cron = "0/30 * * * * ?")
public void doTask(){
logger.info("执行MyTask,时间为:"+new Date(System.currentTimeMillis()));
}
}


没有更多推荐了 [去首页]
image
文章
376
原创
293
转载
83
翻译
0
访问量
183399
喜欢
73
粉丝
5
码龄
7年
资源
3

文章目录

加载中...
0
0