zoukankan      html  css  js  c++  java
  • java定时器学习

    一、这个是利用jdk自带的Thread类的sleep方法实现定时执行任务。

    package tasker;
    
    import java.util.Date;
    
    public class tasker01 extends Thread {
    	private static Date date;
    
    	public static void main(String[] args) {
    		while (true) {
    			try {
    				Thread.sleep((int) (Math.random() * 1000));
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			System.out.println("休眠一秒");
    			date = new Date();
    			System.out.println(date);
    			// 定时执行任务
    		}
    	}
    }
    

    二、利用 Java 自带的定时器任务执行类 java.util.Timer 和 java.util.TimerTask ,实现方式有两种,一种是用java匿名内部类实现,只需一个类即可,关于匿名内部类请参考http://www.cnblogs.com/nerxious/archive/2013/01/25/2876489.html,使用匿名内部类还有个前提条件:必须继承一个父类或实现一个接口。

    package tasker;
    
    import java.util.Date;
    import java.util.Timer;
    
    public class tasker02 {
    	public static void main(String[] args) {
    
    		Timer timer = new Timer();
    		timer.schedule(task, 5000, 2000);
    	}
    	static java.util.TimerTask task = new java.util.TimerTask() {
    
    		@Override
    		public void run() {
    			System.out.println("i am running");
    			Date date = new Date();
    			System.out.println(date);
    		}
    	};
    
    }
    

      第二种方式是新建一个类去继承TimerTask类,需要用两个类解决

    Tasker类

    package tasker;
    
    import java.util.Date;
    import java.util.TimerTask;
    
    public class Tasker extends TimerTask{
    
    	@Override
    	public void run() {
    		System.out.println("i am running");
    		Date date=new Date();
    		System.out.println(date);
    	}
    	
    
    }
    

    main方法类

    package tasker;
    
    import java.util.Timer;
    
    public class tasker02 {
    	public static void main(String[] args) {
    
    		Timer timer = new Timer();
    		timer.schedule(new Tasker(), 5000, 2000);
    	}
    }
    

     再举个例子

    package timer;
    
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class TestTimer {
    	public static void main(String[] args) {
    		System.out.println("About to schedule task.");
    		new Reminder(10);
    		System.out.println("Task scheduled...");
    		Timer timer=new Timer();
    		timer.schedule(new TaskTimer(), 3000);
    	}
    	  public static class Reminder{
    		         Timer timer;
    		           public Reminder(int sec){
    		               timer = new Timer();
    		               timer.schedule(new TimerTask(){
    		                   public void run(){
    		                      System.out.println("Time's up...");
    		                       timer.cancel();
    		                  }
    		               }, sec*1000);
    		         }
    		      } 
    
    }
    
    package timer;
    
    import java.util.TimerTask;
    
    public class TaskTimer extends TimerTask{
    
    	@Override
    	public void run() {
    		int m=4;
    		if(m==4){
    			System.out.println("====");
    		}else{
    			System.out.println("定时器运行.....");
    		}
    	}
    
    }
    

      

      

    三、使用ScheduledExecutorService类,此类改进了简陋的Timer类,Java提供的Time类可以周期性地或者延期执行任务,但是有时我们需要并行执行同样的任务,这个时候如果创建多个Time对象会给系统带来负担,解决办法是将定时任务放到线程池中执行。Java的ScheduledThreadPoolExecutor类实现了ScheduledExecutorService接口中定义的以不同方法执行任务的方法。

    package tasker;
    
    import java.util.Date;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    public class tasker03 {
    
    	public static void main(String[] args) throws InterruptedException {
    		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
    
    		System.out.println("Current Time = " + new Date());
    		for (int i = 0; i < 3; i++) {
    			Thread.sleep(1000);
    			scheduledThreadPool.scheduleWithFixedDelay(task, 10000,2000, TimeUnit.SECONDS);
    		}
    
    		Thread.sleep(30000);
    
    		scheduledThreadPool.shutdown();
    		while (!scheduledThreadPool.isTerminated()) {
    		}
    		System.out.println("Finished all threads");
    	}
    	static java.util.TimerTask task = new java.util.TimerTask() {
    
    		@Override
    		public void run() {
    			System.out.println("i am running");
    			Date date = new Date();
    			System.out.println(date);
    		}
    	};
    
    }
    

       改进版的和多线程有关的定时器,有两个类

    WorkerThread类

    package tasker;
    
    import java.util.Date;
    
    public class WorkerThread implements Runnable {
    	private String command;
    	public WorkerThread(){};
    	public WorkerThread(String command){
    		this.command=command;
    	}
    
    	@Override
    	public void run() {
    		System.out.println(Thread.currentThread().getName()+"start time:"+new Date());
    		processCommand();
    		System.out.println(Thread.currentThread().getName()+"end time:"+new Date());
    	}
    	private void processCommand(){
    		try {
    			Thread.sleep(1000);
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    	}
    	public String toString(){
    		return this.command;
    	}
    
    }
    

     main类

    package tasker;
    
    import java.util.Date;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    public class tasker03 {
    
    	public static void main(String[] args) throws InterruptedException {
    		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
    		System.out.println("Current Time = " + new Date());
    		for (int i = 0; i < 3; i++) {
    			Thread.sleep(1000);
    			WorkerThread task=new WorkerThread("do something");
    			scheduledThreadPool.scheduleWithFixedDelay(task, 10000,2000, TimeUnit.SECONDS);
    		}
    
    		Thread.sleep(30000);
    
    		scheduledThreadPool.shutdown();
    		while (!scheduledThreadPool.isTerminated()) {
    		}
    		System.out.println("Finished all threads");
    	}
    	
    }
    

    四、使用任务调度框架Quartz,官网 http://www.quartz-scheduler.org

    在Spring中的用法:

    引入jar包

    java代码

    package com.coalmine.desktop;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    public class QuartzJob {
     
     public void work() {
      
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date =  new Date();
      System.out.println(sdf.format(date) + "  执行Quartz定时器");
      
     }
    }
    

    applicationContext.xml配置如下:

    <!-- 要调用的工作类 -->
    <bean id="quartzJob" class="com.coalmine.desktop.QuartzJob"></bean>
    
     <!-- 定义调用对象和调用对象的方法 -->
     <bean id="jobtask"   class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
     	<!-- 调用的类 -->
     	<property name="targetObject">    <ref bean="quartzJob" />   </property>
     	<!-- 调用类中的方法 -->
     	<property name="targetMethod">
     	<value>work</value>
     	</property>
     </bean>
     <!-- 定义触发时间 -->
     <bean id="doTime"   class="org.springframework.scheduling.quartz.CronTriggerBean">
      	<property name="jobDetail">    <ref bean="jobtask" />   </property>
      	<!-- cron表达式 -->
      	<property name="cronExpression">
      	<!-- 第 10秒 隔 5秒执行一次-->
      	<value>10/5 * * * * ?</value>
      	</property>
      </bean>
     <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 -->
      <bean id="startQuertz" lazy-init="false" autowire="no"   class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
      	<property name="triggers">
      		<list>   <ref bean="doTime" />  </list>
      	</property>
      </bean>
    

    启动服务后从第10秒开始每隔5秒执行一次work方法

    参考文档:http://www.quartz-scheduler.org/generated/2.2.2/pdf/Quartz_Scheduler_Developer_Guide.pdf

    首先创建要执行的类。

    然后初始化Scheduler,

    SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
    Scheduler sched = schedFact.getScheduler();
    sched.start();

    创建job

     JobDetail job = newJob(HelloJob.class).withIdentity("myJob", "group1").build();

    创建任务执行触发器

     Trigger trigger = newTrigger().withIdentity("myTrigger", "group1").startNow()
    .withSchedule(simpleSchedule()
    .withIntervalInSeconds(40)
    .repeatForever())
    .build();

    安排工作

     // Tell quartz to schedule the job using our trigger
    sched.scheduleJob(job, trigger);

    关闭计划

    sched.shutdown(true);

    ============================================================

    The key interfaces of the Quar� API are:
    Scheduler - the main API for interacting with the Scheduler.
    Job - an interface to be implemented by components that you want the Scheduler to execute.
    JobDetail - used to define instances of Jobs.
    Trigger - a component that defines the schedule upon which a given Job will be executed.
    JobBuilder - used to define/build JobDetail instances, which define instances of Jobs.
    TriggerBuilder - used to define/build Trigger instances.

  • 相关阅读:
    古典密码-移位密码|埃特巴什密码Atbash
    古典密码-凯撒密码Caeser
    古典密码-维吉尼亚密码Vigenere
    使用kubeadm搭建一个k8s集群
    用户态线程和内核态线程的区别
    模板合集
    NoteExpress 章节合并后如何更新参考文献列表?
    CSDN 博客园主题
    GShang的博客园2020年终总结
    【比赛记录】CodeChef January Challenge 2021
  • 原文地址:https://www.cnblogs.com/JAYIT/p/4987871.html
Copyright © 2011-2022 走看看