SpringBoot学习9.1-定时任务

1.定时任务开启

@EnableScheduling启用定时任务

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling // ※ 启用定时任务
public class ScheduleConfig {
}

2.cron表达式设定定时策略

cron顺序:秒 分 时 天 月 周 。
不支持年。
通配符*表示任意值,?表示不指定值,避免日期和星期的冲突
第1列秒(0~59)  
第2列分钟0~59  
第3列小时0~23(0表示子夜)  
第4列日1~31  
第5列月1-12 或者 JAN-DEC  
第6列星期1-7 或者 SUN-SAT(1表示星期天) 

举例:

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/** 定时任务 */
@Component // ※ 必须装配到IoC
public class ScheduleTaskService {
	// 每5秒执行一次
	@Scheduled(fixedRate = 5000)
	public void job1() { // ※ 必须用public修饰
		System.out.println("执行job1,时刻=" + System.currentTimeMillis());
	}
	// 每10秒执行一次
	@Scheduled(fixedRate = 10000)
	@Async // 异步调用(异步线程池)
	public void job2() {
		System.out.println("执行job1,时刻=" + System.currentTimeMillis());
	}
	// 每分钟的1秒执行
	@Scheduled(cron = "1 * * * * ?")
	public void job3() {
		System.out.println("执行job3,时刻=" + System.currentTimeMillis());
	}
	// 每天零点执行
	@Scheduled(cron = "0 0 0 * * ? ")
	public void job4() {
		System.out.println("执行job4,时刻=" + System.currentTimeMillis());
	}
	// 周五,23点30分,0秒,执行
	@Scheduled(cron = "0 30 23 ? * 6")
	public void job5() {
		System.out.println("执行job5");
	}
}

 

github:https://github.com/zhangyangfei/SpringBootLearn.git中的springTech工程。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值