1、创建定时任务:
@Component
public class AutonotifyController {
private ThreadUtil getThreadUtil() {
ThreadUtil threadUtil = SpringContextUtil.getBean("threadUtil");
return threadUtil;
}
@Scheduled(cron = "*/5 * * * * ?")
public void AutonotifyStartChargeResult() {
getThreadUtil().AutonotifyStartChargeResult();
}
@Scheduled(cron = "*/50 * * * * ?")
public void AutonotifyChargeStatus() {
getThreadUtil().AutonotifyChargeStatus();
}
@Scheduled(cron = "*/5 * * * * ?")
public void AutonotifyStopChargeResult() {
getThreadUtil().AutonotifyStopChargeResult();
}
@Scheduled(cron = "*/5 * * * * ?")
public void AutonotifyOrderInfo() {
getThreadUtil().AutonotifyOrderInfo();
}
@Scheduled(fixedRate = 200)
public void checkGunStatus() {
getThreadUtil().checkGunStatus();
}
@Scheduled(cron = "*/5 * * * * ?")
public void ActiveOrderAddAndDelete() {
getThreadUtil().ActiveOrderAddAndDelete();
}
@Scheduled(cron = "*/5 * * * * ?")
public void EndOrderAddAndDelete() {
getThreadUtil().EndOrderAddAndDelete();
}
}
使用 @Scheduled来创建定时任务 这个注解用来标注一个定时任务方法。
通过看 @Scheduled源码可以看出它支持多种参数:
(1)cron:cron表达式,指定任务在特定时间执行;
(2)fixedDelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
(3)fixedDelayString:与fixedDelay含义一样,只是参数类型变为String;
(4)fixedRate:表示按一定的频率执行任务,参数类型为long,单位ms;
(5)fixedRateString: 与fixedRate的含义一样,只是将参数类型变为String;
(6)initialDelay:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
(7)initialDelayString:与initialDelay的含义一样,只是将参数类型变为String;
(8)zone:时区,默认为当前时区,一般没有用到。
2、开启定时任务:
@SpringBootApplication
@EnableScheduling
public class PositivebuttjointApplication extends SpringBootServletInitializer
{
public static void main(String[] args)
{
SpringApplication.run(PositivebuttjointApplication.class, args);
}
注:这里的 @EnableScheduling 注解,它的作用是发现注解 @Scheduled的任务并由后台执行。没有它的话将无法执行定时任务。
引用官方文档原文:
@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.
3、执行结果(单线程)
就完成了一个简单的定时任务模型,下面执行springBoot观察执行结果:
从控制台输入的结果中我们可以看出所有的定时任务都是在同一个线程池用同一个线程来处理的,那么我们如何来并发的处理各定时任务呢,请继续向下看。
4、多线程处理定时任务:
1.开启多线程
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class PositivebuttjointApplication extends SpringBootServletInitializer
{
public static void main(String[] args)
{
SpringApplication.run(PositivebuttjointApplication.class, args);
}
加入@EnableAsync开启多线程
2.使用多线程
@Async
public void AutonotifyStartChargeResult() {
}
调用的方法上加上@Async使用多线程
3.配置连接池
@Configuration
public class ScheduleConfiguration implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(this.getTaskScheduler());
}
private ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(20);
taskScheduler.setThreadNamePrefix("schedule-pool-");
taskScheduler.initialize();
return taskScheduler;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



