spring boot---创建定时任务

1.@Scheduled创建定时任务,在springBoot主类中加入@EnableScheduling注解启用定时任务的配置,备注:不支持集群,集群可以使用xxl-job

2.首先创建一个task包和一个类,这个类中创建一个方法来进行定时任务

 3.需要在启动类中启动我们的定时任务

 4.启动之后我们来看看效果,如果是需要用正则进行匹配,可以在这里进行你需要的表达式https://www.bejson.com/othertools/cron

package demo.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

//把普通pojo实例化到spring容器中,相当于配置文件中的
//<bean id="" class=""/>
@Component
@Slf4j
public class ScheduledTasks {
//设置定时任务的时间,每隔3秒执行到taskService中的内容
//@Scheduled(cron = "* * * * * *") cron表达式,{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}
//“30 * * * * ?” 每半分钟触发任务
//“30 10 * * * ?” 每小时的10分30秒触发任务
//“30 10 1 * * ?” 每天1点10分30秒触发任务
//“30 10 1 20 * ?” 每月20号1点10分30秒触发任务

@Scheduled(fixedRate=3000)
public void taskService(){
//打印当前时间
log.info("<<定时任务>>"+System.currentTimeMillis());
}
}



沫笙
原文地址:https://www.cnblogs.com/wendy-0901/p/14356589.html