1、主启动类加上注解,开启定时任务
@EnableScheduling
2、创建定时任务类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.china.statistics.service.StatisticsDailyService;
import com.china.statistics.util.DateUtil;
@Component
public class ScheduledTask {
// 每5秒执行一次,@Scheduled注解表示方法为定时执行的任务
@Scheduled(cron = "0/5 * * * * ?")
public void task1() {
System.out.println("定时任务执行****************************");
}
@Autowired
private StatisticsDailyService statisticsDailyService;
// 每天凌晨1点执行
@Scheduled(cron = "0 0 1 * * ? ")
public void task2() {
Date date = DateUtil.addDays(new Date(), -1);
String time = DateUtil.formatDate(date);
statisticsDailyService.createStatistics(time);
}
}
注:@Scheduled(cron = "0 0 1 * * ? ")这个注解里面的cron 叫做七域表达式,表达式的内容定义了执行定时任务的规则,这个规则无需自己记忆,可以直接使用工具生成,以下是该工具的网页链接,也可使用其他工具。
以下附上一个时间的工具类,可用在定时任务中。
package com.china.statistics.util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 日期操作工具类
*
* @author qy
* @since 1.0
*/
public class DateUtil {
private static final String dateFormat = "yyyy-MM-dd";
/**
* 格式化日期
*
* @param date
* @return
*/
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(date);
}
/**
* 在日期date上增加amount天 。
*
* @param date 处理的日期,非null
* @param amount 要加的天数,可能为负数
*/
public static Date addDays(Date date, int amount) {
Calendar now =Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE,now.get(Calendar.DATE)+amount);
return now.getTime();
}
public static void main(String[] args) {
System.out.println(DateUtil.formatDate(new Date()));
System.out.println(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
}
}