1.Timer
使用Java自带的类来实现简单的定时任务
自定义一个类继承TimerTask
package com.example.demo.schedule;
import org.springframework.stereotype.Component;
import java.util.TimerTask;
//自定义一个类继承TimerTask
@Component
public class TimerService extends TimerTask {
//定时任务要做的事情
@Override
public void run() {
for (int i=0;i<3;i++){
System.out.println(i);
}
}
}
延迟2秒执行,每隔3秒打印 0 1 2
package com.example.demo.controller;
import com.example.demo.config.HttpResponse;
import com.example.demo.schedule.TimerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Timer;
@RestController
public class TimerController {
@Autowired
private TimerService timerService;
@GetMapping("/time")
public HttpResponse getTimerTask(){
Timer timer = new Timer();
timer.schedule(timerService,2000,3000);
return HttpResponse.ok();
}
}
2.SpringTask
@Scheduled+@EnableScheduling
package com.example.demo.schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class ScheduledService {
@Scheduled(fixedRate = 3000)
public void scheduled1(){
log.info("222");
}
}
每隔3秒执行一次
启动类上加上@EnableScheduling注解
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3.SpringTask多线程任务
@EnableAsync+@Async
用一个线程来执行多个任务,如果一个任务卡住了,那么其他任务的执行也会受影响,所以我们可以采用多线程的方式
package com.example.demo.schedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@Slf4j
@EnableAsync
public class ScheduledService {
@Async
@Scheduled(fixedRate = 5000)
public void scheduled1() throws InterruptedException {
log.info("222");
Thread.sleep(10000);
}
@Async
@Scheduled(fixedRate = 2000)
public void scheduled(){
log.info("333");
}
}
启动类不变
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
任务的执行时间不受其本身执行时间的限制,任务和任务之间也互不影响
4.Quartz
这个方法暂时不讲,稍微有点复杂,感兴趣的可以自主学习学习