一、Timer
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 at: " + System.currentTimeMillis());}};// 在延迟一段时间后执行任务timer.schedule(task, 1000,1000); // 1秒后执行 、每秒执行一次}
}
二、Excutors
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;public class ScheduledExecutorExample {public static void main(String[] args) {ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);Runnable task = () -> {System.out.println("Task executed at: " + System.currentTimeMillis());};// 在延迟一段时间后执行任务,然后每隔一段时间重复执行scheduler.scheduleAtFixedRate(task, 1, 1, TimeUnit.SECONDS);}
}
三、quartz框架
< dependency> < groupId> org.quartz-scheduler</ groupId> < artifactId> quartz</ artifactId> < version> 2.3.2</ version>
</ dependency>
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;public class QuartzExample {public static void main(String[] args) throws SchedulerException {Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();JobDetail job = JobBuilder.newJob(MyJob.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();}
}class MyJob implements Job {@Overridepublic void execute(JobExecutionContext context) throws JobExecutionException {System.out.println("Job executed at: " + System.currentTimeMillis());}
}
四、springboot中@Schedule注解