1、schedule 注解定时器
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.util.Date;
/**
* 注解 定时器
*
*/
@Component
@Configuration
@EnableScheduling
public class FirstSecheduler {
//五秒 运行一次
@Scheduled(cron = "0/5 * * * * ?")
public void fiveSeconds(){
System.out.println("start:"+new Date().getSeconds());
System.out.println("你好啊");
System.out.println("end:"+new Date().getSeconds());
}
}
2、动态定时器 可配置间隔时间 和内容
/**
* 实现sechedule
*/
@Component
@Configuration
@EnableScheduling
public class SecondSchedule implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.addTriggerTask(() ->System.out.println("执行动态定时任务: " + new Date()),
triggerContext -> {
//2.1 从数据库获取执行周期
String cron = "0/5 * * * * ?";
//2.3 返回执行周期(Date)
return new CronTrigger(cron).nextExecutionTime(triggerContext);
}
);
}
}
3、使用多线程定时器
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.util.Date;
/**
* 多线程定时任务
*/
@Component
@EnableScheduling //开启定时器
@EnableAsync //开启多线程
public class ThreeSChedule {
@Async
@Scheduled(fixedDelay = 1000)
public void first(){
System.out.println("first:"+new Date().toLocaleString());
}
@Async
@Scheduled(fixedDelay = 1000)
public void second(){
System.out.println("second:"+new Date().toLocaleString());
}
}
4、使用外部 quartz定时
pom配置
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.1</version>
</dependency>
import java.util.Date;
/**
* 定义任务类 实现 Job 接口
*/
public class FirstQuartz implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("quartz"+new Date().toLocaleString());
}
}
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
/**
* 主函数调用quartz
*/
public class QuartzMain {
public static void main(String[] args) throws Exception{
//创建job对象
JobDetail jobDetail = JobBuilder.newJob(FirstQuartz.class).build();
//触发时间
Trigger trigger = TriggerBuilder.newTrigger().withSchedule(
CronScheduleBuilder.cronSchedule("0/2 * * * * ?")).build();
//作业内容
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.scheduleJob(jobDetail,trigger);
//启动
scheduler.start();
}
}
可根据不同需求使用
以上是自学总结。有借鉴前辈帖子望见谅。不足之处请多多指教
联系客服