Java实现执行任务调度(定时执行某个方法)

  1. 在启动类添加注解:@EnableScheduling //允许自动调用
@SpringBootApplication
@EnableScheduling //允许自动调用
public class ManageApplication {

	public static void main(String[] args) {
		SpringApplication.run(ManageApplication.class, args);
	}
}
  1. 在需要使用任务调度的类上面加注解 @Component,使该类被Spring管理
import org.springframework.stereotype.Component;
 
@Component
public class Ds {
    //方法1 {...}
    //方法2 {...}
    //....
}

3.任务调度的方法上面加注解 @Scheduled

  1. cron属性:时间表达式

  2. fixedRate属性:上一个调用开始后再次调用的延时(再次调用时不需要等上一个调用执行完成)

  3. fixedDelay属性:上一个调用完成后再次调用的延时(再次调用时需要等上一个调用执行完成)

  4. initialDelay属性:第一次调用时的延迟时间

属性	含义
fixedRate = 1000	每秒执行一次,单位毫秒
"0 0 10,14,16 * * ?"	每天10点、14点、16点 触发
"0 0/30 9-17 * * ?"	朝九晚五工作时间内每半小时触发
"0 0 12 ? * WED"	表示每个星期三中午12点触发
"0 0 12 * * ?"	每天中午12点触发
"0 15 10 ? * *"	每天上午10:15触发
"0 15 10 * * ?"	每天上午10:15触发
"0 15 10 * * ? *"	每天上午10:15触发
"0 15 10 * * ? 2005"	2005年的每天上午10:15触发
"0 * 14 * * ?"	在每天下午2点到下午2:59期间的每1分钟触发
"0 0/5 14 * * ?"	在每天下午2点到下午2:55期间的每5分钟触发
"0 0/5 14,18 * * ?"	在每天下午2点到2:55期间和下午6点到6:55期间的每5分钟触发
"0 0-5 14 * * ?"	在每天下午2点到下午2:05期间的每1分钟触发
"0 10,44 14 ? 3 WED"	每年三月的星期三的下午2:102:44触发
"0 15 10 ? * MON-FRI"	周一至周五的上午10:15触发
"0 15 10 15 * ?"	每月15日上午10:15触发
"0 15 10 L * ?"	每月最后一日的上午10:15触发
"0 15 10 ? * 6L"	每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6L 2002-2005"	2002年至2005年的每月的最后一个星期五上午10:15触发
"0 15 10 ? * 6#3"	每月的第三个星期五上午10:15触发
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
@Component
public class Ds {
 
	//每1秒执行一次该方法
	@Scheduled(fixedRate = 1000)
	public void test() {
		System.out.println("------定时调度------");
	}
	
	//每天12点执行一次该方法
	@Scheduled("0 0 12 * * ?")
	public void test2() {
		System.out.println("------定时调度2------");
	}
	
}

通常情况下,任务调度需要配合异步功能,所以类只需要再添加一个注解@EnableAsync

import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.EnableAsync;
 
@Component
@EnableAsync
public class Ds {
 
	//每1秒执行一次该方法
	@Scheduled(fixedRate = 1000)
	public void test() {
		System.out.println("------定时调度------");
	}
	
	//每天12点执行一次该方法
	@Scheduled("0 0 12 * * ?")
	public void test2() {
		System.out.println("------定时调度2------");
	}
	
}

参考

Java实现执行任务调度(定时执行某个方法)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛歌依旧fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值