第一种方式:
spring框架,编写定时任务类,构造函数里使用Timer创建定时任务,然后扫描该类所在jar包
package scheduledTasks; import java.util.Timer; import java.util.TimerTask; import org.springframework.stereotype.Component; @Component public class TimedTask { TimedTask(){ try { //第一个参数是任务,第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间,时间单位是毫秒 new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { System.out.println("定时任务执行"); } }, 0L, 1000L); } catch (Exception e) { e.printStackTrace(); } } }
第二种方式:使用java.util.concurrent.ScheduledThreadPoolExecutor结合org.apache.commons.lang3.concurrent.BasicThreadFactory(推荐使用)
package haiyang.yu.timer; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import java.util.Date; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created on 2018-04-20 13:09 * <p>Title: haiyang.yu.timer</p> * <p> 使用这种方案,需要引入common-lang3的jar包 <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.6</version> </dependency> * </p> * * @author <a href="mailto:991138518@qq.com">yuhaiyang</a> * @version 1.0 */ public class TimedTask { private static void useScheduledThreadPoolExecutorImplTimedTask(){ ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor( 1, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(false).build()); // 第一个参数是任务,第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间,第四个参数是时间单位 scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("Local Time is " + new Date().toString()); } }, 0L, 1L, TimeUnit.SECONDS); } public static void main(String[] args) { useScheduledThreadPoolExecutorImplTimedTask(); } }
第三种方式:使用java.lang.Thread,这种方式使用的最多,但也是最lower的。
package haiyang.yu.timer; import java.util.Date; /** * Created on 2018-04-20 13:09 * <p>Title: haiyang.yu.timer</p> * <p>Description: </p> * * @author <a href="mailto:991138518@qq.com">yuhaiyang</a> * @version 1.0 */ public class TimedTask { private static void useThreadImplTimedTask(){ Runnable runnable = new Runnable() { @Override public void run() { while (true) { System.out.println("Local Time is " + new Date().toString()); try { //时间间隔,单位是毫秒 Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } } } }; Thread thread = new Thread(runnable); thread.start(); } public static void main(String[] args) { useThreadImplTimedTask(); } }