Springboot项目中定时任务的四种实现方式
在Spring Boot项目中,实现定时任务的四种常见方式如下:
- 使用
@Scheduled
注解:
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
@Scheduled(fixedRate = 5000)
public void executeTask() {
// 定时任务的逻辑
System.out.println("Fixed rate task");
}
}
- 使用
ScheduledExecutorService
:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Configuration
public class ScheduledTaskConfiguration {
@Bean
public ScheduledExecutorService scheduledExecutorService() {
return Executors.newScheduledThreadPool(5);
}
public void startScheduledTask(ScheduledExecutorService executorService) {
Runnable task = () -> System.out.println("Scheduled task with ExecutorService");
executorService.scheduleAtFixedRate(task, 0, 5, TimeUnit.SECONDS);
}
}
- 使用
TaskScheduler
:
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Component;
@Component
public class TaskSchedulerTask {
private TaskScheduler taskScheduler;
public TaskSchedulerTask(TaskScheduler taskScheduler) {
this.taskScheduler = taskScheduler;
}
public void startTask() {
Runnable task = () -> System.out.println("Scheduled task with TaskScheduler");
taskScheduler.scheduleAtFixedRate(task, 5000);
}
}
- 使用
Quartz
:
首先添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
然后实现定时任务:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class QuartzJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Quartz job executed");
}
}
配置定时任务:
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.schedu
评论已关闭