标签:builder run 创建 class 定时任务 edr timer main jar
1 public class Demo01 { 2 static long count = 0; 3 public static void main(String[] args) { 4 Runnable runnable = new Runnable() { 5 @Override 6 public void run() { 7 while (true) { 8 try { 9 Thread.sleep(1000); 10 count++; 11 System.out.println(count); 12 } catch (Exception e) { 13 // TODO: handle exception 14 } 15 } 16 } 17 }; 18 Thread thread = new Thread(runnable); 19 thread.start(); 20 } 21 }
1 /** 2 * 使用TimerTask类实现定时任务 3 */ 4 public class Demo02 { 5 static long count = 0; 6 7 public static void main(String[] args) { 8 TimerTask timerTask = new TimerTask() { 9 10 @Override 11 public void run() { 12 count++; 13 System.out.println(count); 14 } 15 }; 16 Timer timer = new Timer(); 17 // 天数 18 long delay = 0; 19 // 秒数 20 long period = 1000; 21 timer.scheduleAtFixedRate(timerTask, delay, period); 22 } 23 24 }
1 public class Demo003 { 2 public static void main(String[] args) { 3 Runnable runnable = new Runnable() { 4 public void run() { 5 // task to run goes here 6 System.out.println("Hello !!"); 7 } 8 }; 9 ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); 10 // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间 11 service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS); 12 } 13 }
Quartz定时任务
1、引入jar包
1 <dependencies> 2 <!-- quartz --> 3 <dependency> 4 <groupId>org.quartz-scheduler</groupId> 5 <artifactId>quartz</artifactId> 6 <version>2.2.1</version> 7 </dependency> 8 <dependency> 9 <groupId>org.quartz-scheduler</groupId> 10 <artifactId>quartz-jobs</artifactId> 11 <version>2.2.1</version> 12 </dependency> 13 </dependencies>
1 public class MyJob implements Job { 2 public void execute(JobExecutionContext context) throws JobExecutionException { 3 System.out.println("quartz MyJob date:" + new Date().getTime()); 4 } 5 }
1 //1.创建Scheduler的工厂 2 SchedulerFactory sf = new StdSchedulerFactory(); 3 //2.从工厂中获取调度器实例 4 Scheduler scheduler = sf.getScheduler(); 5 6 7 //3.创建JobDetail 8 JobDetail jb = JobBuilder.newJob(MyJob.class) 9 .withDescription("this is a ram job") //job的描述 10 .withIdentity("ramJob", "ramGroup") //job 的name和group 11 .build(); 12 13 //任务运行的时间,SimpleSchedle类型触发器有效 14 long time= System.currentTimeMillis() + 3*1000L; //3秒后启动任务 15 Date statTime = new Date(time); 16 17 //4.创建Trigger 18 //使用SimpleScheduleBuilder或者CronScheduleBuilder 19 Trigger t = TriggerBuilder.newTrigger() 20 .withDescription("") 21 .withIdentity("ramTrigger", "ramTriggerGroup") 22 //.withSchedule(SimpleScheduleBuilder.simpleSchedule()) 23 .startAt(statTime) //默认当前时间启动 24 .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次 25 .build(); 26 27 //5.注册任务和定时器 28 scheduler.scheduleJob(jb, t); 29 30 //6.启动 调度器 31 scheduler.start();
标签:builder run 创建 class 定时任务 edr timer main jar
原文地址:https://www.cnblogs.com/yuhuiqing/p/11785209.html