使用 java.util.Timer
和 java.util.TimerTask
:
Timer
是一个定时器工具,能够在后台线程中调度任务。TimerTask
是一个实现了Runnable
接口的抽象类,需要继承它并重写run
方法。
示例代码:
import java.util.Timer;
import java.util.TimerTask;public class TimerExample {public static void main(String[] args) {Timer timer = new Timer();TimerTask task = new TimerTask() {@Overridepublic void run() {System.out.println("Task executed!");}};// Schedule the task to run every 2 seconds with an initial delay of 1 secondtimer.schedule(task, 1000, 2000);}
}
使用 ScheduledExecutorService
:
ScheduledExecutorService
是java.util.concurrent
包中的接口,提供了一种更强大的机制来调度任务。
示例代码:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;public class ScheduledExecutorServiceExample {public static void main(String[] args) {ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);Runnable task = new Runnable() {@Overridepublic void run() {System.out.println("Task executed!");}};// Schedule the task to run every 2 seconds with an initial delay of 1 secondscheduler.scheduleAtFixedRate(task, 1, 2, TimeUnit.SECONDS);}
}
使用 Quartz:
- Quartz 是一个功能强大且灵活的开源任务调度框架。
示例代码:
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.JobBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.SimpleScheduleBuilder;public class QuartzExample {public static class HelloJob implements Job {@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {System.out.println("Hello, Quartz!");}}public static void main(String[] args) throws SchedulerException {Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("myJob", "group1").build();Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(2).repeatForever()).build();scheduler.scheduleJob(job, trigger);scheduler.start();}
}
以上是三种常见的定时任务实现方法,每种方法都有其优缺点,可以根据具体需求选择合适的方案。