一.创建定时任务类,使用cron表达式
package com.wxit.staservice.scheduled;
import com.wxit.staservice.service.StatisticsDailyService;
import com.wxit.staservice.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
- @author wj
- @date 2021.12.25 15:14
*/
@Component
public class ScheduledTask {
@Autowired
private StatisticsDailyService statisticsDailyService;
/**
* 测试
* 每天七点到二十三点每五秒执行一次
*/
@Scheduled(cron = "0/5 * * * * ?")
public void task1() {
System.out.println("*********++++++++++++*****执行了");
}
/**
* 每天凌晨1点执行定时
*/
@Scheduled(cron = "0 0 1 * * ?")
public void task2() {
//获取上一天的日期
String day = DateUtil.formatDate(DateUtil.addDays(new Date(), -1));
statisticsDailyService.registerCount(day);
}
}
二.在启动类上添加注解
package com.wxit.staservice;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
- @author wj
- @date 2021.12.24 14:40
*/
@SpringBootApplication
@ComponentScan(basePackages = {"com.wxit"})
@EnableFeignClients
@EnableDiscoveryClient
@MapperScan("com.wxit.staservice.mapper")
@EnableScheduling //开启定时任务
public class StaApplication {
public static void main(String[] args) {
SpringApplication.run(StaApplication.class,args);
}
}
三.在线生成corn表达式
http://cron.qqe2.com/
具体生成规则见官网教程