Java中可以实现的定时任务策略
文章目录
- Java中可以实现的定时任务策略
- 自定义独立线程
- JDK提供的调度线程池-**ScheduledExecutorService**
- 内核是Spring的Task执行调度
- quartz调度
自定义独立线程
package com.example.demo;import java.util.concurrent.atomic.AtomicBoolean;public class SimpleTask {private final AtomicBoolean started = new AtomicBoolean(false);Thread scheduledThread = new Thread(this::doSchedule, "SimpleTask");private void doSchedule() {while (started.get()) {System.out.println(Thread.currentThread().getName() + ":哒哒哒...");}}private void stop() throws InterruptedException {if (!started.get()) {throw new IllegalStateException(scheduledThread.getName() + "未启动!");}if (started.compareAndSet(true, false)) {System.out.println(scheduledThread.getName() + ":关闭");}if (Thread.currentThread() != scheduledThread) {scheduledThread.join();}}public static void main(String[] args) throws InterruptedException {SimpleTask s = new SimpleTask();if (s.started.compareAndSet(false, true)) {s.scheduledThread.start();}System.out.println(Thread.currentThread().getName() + ":" + s.started.get());Thread.sleep(200);s.stop();System.out.println(Thread.currentThread().getName() + ":" + s.started.get());}}
结果
main:true
SimpleTask:哒哒哒...
SimpleTask:哒哒哒...
SimpleTask:哒哒哒...
SimpleTask:哒哒哒...
SimpleTask:关闭
main:false
JDK提供的调度线程池-ScheduledExecutorService
package com.example.demo;import com.google.common.util.concurrent.ThreadFactoryBuilder;import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;public class ScheduledExecutorTask {public static void main(String[] args) throws InterruptedException {ScheduledExecutorService service = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().setNameFormat("ScheduledThreadPool-%d").build());service.scheduleAtFixedRate(() -> System.out.println(Thread.currentThread().getName() + ":哒哒哒..哒..哒哒..哒..."), 1, 1, TimeUnit.SECONDS);Thread.sleep(6000);service.shutdown();}
}
ScheduledThreadPool-0:哒哒哒..哒..哒哒.哒...
ScheduledThreadPool-0:哒哒哒..哒..哒哒.哒...
ScheduledThreadPool-0:哒哒哒..哒..哒哒.哒...
ScheduledThreadPool-0:哒哒哒..哒..哒哒.哒...
ScheduledThreadPool-0:哒哒哒..哒..哒哒.哒...
ScheduledThreadPool-0:哒哒哒..哒..哒哒.哒...
内核是Spring的Task执行调度
内核是Spring的Task执行调度说明:https://docs.spring.io/spring-framework/reference/integration/scheduling.html
以SpringBoot为例
开启调度
使用@EnableScheduling
配置启动类,开启任务调度
@SpringBootApplication
@EnableScheduling
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
开发调度任务
package com.example.demo;import java.text.SimpleDateFormat;
import java.util.Date;import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;@Component
public class ScheduledTasks {private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");// 简单的时间间隔执行@Scheduled(fixedRate = 5000)public void reportCurrentTime() {log.info("The time is now {}", dateFormat.format(new Date()));}//使用cron表达式进行调度周期控制@Scheduled(cron = "0/5 * * * * ?")public void cron() {log.info("{}", "哒哒哒...");}
}
quartz调度
以SpringBoot为例集成quartz
<!-- 任务调度quartz-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
开发任务
实现quartz的Job接口
package com.example.demo;import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;import javax.annotation.Resource;
import java.util.List;@Slf4j
public class SampleJob implements Job {@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {log.info("SampleJob is execute");}
}
Quartz任务注册
@Resourceprivate Scheduler scheduler;
try {String groupName = "group-"+SampleJob.class.getName();String name = SampleJob.class.getName();// 构建触发器的KeyTriggerKey triggerKey = TriggerKey.triggerKey(name, groupName);Trigger trigger = scheduler.getTrigger(triggerKey);if (null == trigger) {// 创建任务(Job的实现类)JobDetail jobDetail = JobBuilder.newJob(SampleJob.class).withIdentity(name, groupName).build();// 使用Cron表达式定义触发规则CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0 0/30 * * * ?").withMisfireHandlingInstructionFireAndProceed();// 创建触发器trigger = TriggerBuilder.newTrigger().withIdentity(name, groupName).withSchedule(scheduleBuilder).build();// 将触发器和任务绑定到调度器内scheduler.scheduleJob(jobDetail, trigger);LOG.info("Quartz 创建了job: {}", jobDetail.getKey());} else {LOG.info("job: {} 已存在", trigger.getKey());}} catch (Exception e) {LOG.error("quartz异常:{},{}", e.getMessage(), e);}
Quartz 支持集群模式(分布式任务的调度),持久化方式是 JDBC,将数据持久化到数据库。