每天点滴努力,成就编程路!
定时任务,就是一段程序在某个时间内启动起来。它可以用来统计数据,移动数据,发通知,相当于一个闹钟。
package com.sise.demo1.demo.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* author zxq
* date 2020/7/30 23:50
*/
@Component
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
public class SingleScheduleTask {
//3.添加定时任务,5秒一次
@Scheduled(cron = "0/5 * * * * ?")
private void configureTasks(){
System.out.println("执行静态定时任务时间"+ LocalDateTime.now());
}
}
package com.sise.demo1.demo.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* author zxq
* date 2020/7/31 0:32
*/
@Component
@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {
//执行任务
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(
() -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
//2.设置执行周期(Trigger)
triggerContext -> {
//2.1 从数据库获取执行周期
String cron = "0/2 * * * * ?";
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
package com.sise.demo1.demo.common.config;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* author zxq
* date 2020/7/31 0:37
*/
@Component
@EnableScheduling // 1.开启定时任务
@EnableAsync // 2.开启多线程
public class MultiThreadScheduleTask {
@Async
@Scheduled(fixedDelay = 1000) //间隔1秒
public void first() throws InterruptedException {
System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
Thread.sleep(1000 * 10);
}
@Async
@Scheduled(fixedDelay = 2000)
public void second() {
System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
System.out.println();
}
}
第一步,首先,创建出跑的任务
package com.sise.demo1.demo.common.config.task;
import com.sise.demo1.demo.common.utils.DateUtils;
/**
* author zxq
* date 2020/7/31 0:57
*/
public class MyRunnable1 implements Runnable {
@Override
public void run() {
System.out.println("first DynamicTask," + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss")+Thread.currentThread().getName());
}
}
package com.sise.demo1.demo.common.config.task;
import com.sise.demo1.demo.common.utils.DateUtils;
/**
* author zxq
* date 2020/7/31 0:58
*/
public class MyRunnable2 implements Runnable {
@Override
public void run() {
System.out.println("second DynamicTask," + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss")+Thread.currentThread().getName());
}
}
第二步,写配置类
package com.sise.demo1.demo.common.config.task;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.stereotype.Component;
/**
* author zxq
* date 2020/7/31 0:54
*/
@Component
@EqualsAndHashCode(callSuper = false)
public class TaskConfiguration {
private String corn1;
private String corn2;
public String getCorn1() {
return "0/10 * * * * ?";
}
public String getCorn2() {
return " 0/5 * * * * ?";
}
}
第三步,写控制器
package com.sise.demo1.demo.controller.config;
import com.sise.demo1.demo.common.ResultVO;
import com.sise.demo1.demo.common.config.task.MyRunnable1;
import com.sise.demo1.demo.common.config.task.MyRunnable2;
import com.sise.demo1.demo.common.config.task.TaskConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;
/**
* author zxq
* date 2020/7/31 1:00
*/
@RestController
@RequestMapping(value = "/task")
public class TaskController {
@Autowired
private TaskConfiguration taskConfiguration;
private ScheduledFuture<?> future1;
private ScheduledFuture<?> future2;
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(20);
scheduler.setThreadNamePrefix("task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
scheduler.initialize();
return scheduler;
}
@RequestMapping(value = "/start1")
public ResultVO startScheduler1(){
future1 = threadPoolTaskScheduler().schedule(new MyRunnable1(), new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
return new CronTrigger(taskConfiguration.getCorn1()).nextExecutionTime(triggerContext);
}
});
System.out.println("startScheduler1");
return ResultVO.getSuccess("startScheduler1 success");
}
@RequestMapping(value = "/stop1")
public ResultVO stopScheduler1(){
if(future1 != null){
future1.cancel(true);
}
System.out.println("stopScheduler1");
return ResultVO.getSuccess("startScheduler1 stop");
}
@RequestMapping(value = "/start2")
public ResultVO startScheduler2(){
future2 = threadPoolTaskScheduler().schedule(new MyRunnable2(), new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
return new CronTrigger(taskConfiguration.getCorn2()).nextExecutionTime(triggerContext);
}
});
System.out.println("startScheduler2");
return ResultVO.getSuccess("startScheduler2 success");
}
@RequestMapping(value = "/stop2")
public ResultVO stopScheduler2(){
if(future2 != null){
future2.cancel(true);
}
System.out.println("stopScheduler2");
return ResultVO.getSuccess("startScheduler2 stop");
}
}
此处已经完成定时任务的编写
遗留问题,定时的时间可通过建立配置表,可通过接口暴露给前端进行编辑修改。