I. Overview of the Timer
In Java development, there are some requirements that need to be timed or delayed to perform certain tasks, and we can use the Timer class in Java.
Second, the timer introduction
Timer是一个定时器类,通过该类可以为指定的定时任务进行配置,所在jar包路径:java.util.TimerTimer定时器实例有多种构造方法:Timer()// 创建一个新计时器Timer(boolean isDaemon)//创建一个新计时器,可以指定其相关的线程作为守护程序运行Timer(String name)//创建一个新计时器,其相关的线程具有指定的名称Timer(String name,boolean isDaemon)//创建一个新计时器,其相关的线程具有指定的名称,并且可以指定作为守护程序运行TimerTask类是一个定时任务类,该类实现了Runnable接口,而且是一个抽象类,所在jar包路径:java.util.TimerTask// 可以通过继承该类,来实现自己的定时任务。publicabstractclassTimerTaskimplementsRunnable
Iii. Common methods of timer
Perform a task at a specific time, only once
public void schedule(TimerTask task,Date time)
Perform a task after a certain time, only once
public void schedule(TimerTask task, long delay)
Specify the time for the first execution, and then repeat the time interval
public void schedule(TimerTask task, Date firstTime, long period)
Executes for the first time after a specific delay, and then repeats in intervals
publicvoid schedule(TimerTask task,long delay,long period)/*参数说明 delay: 延迟执行的毫秒数,即在delay毫秒之后第一次执行 period:重复执行的时间间隔*/
After the first execution, the specific frequency executes, the same as the 3 effect
publicvoid scheduleAtFixedRate(TimerTask task,Date firstTime,long period)
Executes the first time after delay milliseconds, followed by a specific frequency
publicvoid scheduleAtFixedRate(TimerTask task,long delay,long period)
Timer logoff
timer.cancel();
The difference between schedule () and Scheduleatfixedrate ()
schedule()
The method is more focused on maintaining the stability of the interval time: guaranteed to be called once every period time
scheduleAtFixedRate()
The method is more focused on maintaining the stability of the execution frequency: The frequency of multiple calls is approaching period time, and if the task execution time is greater than period, the next task is executed immediately after the task is executed.
Iv. Examples of timer usage
Use a timer to print data every 2 seconds, and the task starts 1 seconds after the timer starts
import java.util.Timer;import java.util.TimerTask;publicclassTestTimer{publicstaticvoid main(String[] args){Timer timer =newTimer(); timer.schedule(newMyTask(),1000,2000);}}classMyTaskextendsTimerTask{@Overridepublicvoid run(){System.out.println("每隔2秒我就出现一次……");}}
Use a timer to randomly generate numbers at random intervals
import java.util.Timer;import java.util.Random;import java.util.TimerTask;publicclassTimerTest{publicstaticvoid main(String[] args){Timer timer =newTimer();NewTimerTask timerTask =newNewTimerTask();//程序运行后立刻执行任务,每隔100ms执行一次 timer.schedule(timerTask,0,100);}}classNewTimerTaskextendsTimerTask{@Overridepublicvoid run(){ createRandomNumber(); createRandomNumberFromMathRandom();}//用纯Math中的方法来随机生成1-10之间的随机数privatevoid createRandomNumberFromMathRandom(){int j =(int)(Math.round(Math.random()*10+1));System.out.println("随机生成的数字为:"+j);}//用Random类的方式来随机生成1-10之间的随机数privatevoid createRandomNumber(){Random random =newRandom(System.currentTimeMillis());int value = random.nextInt(); value =Math.abs(value); value = value%10+1;System.out.println("新生成的数字为:"+ value);}}
V. Summary
Using the two simple examples above, we can clearly know the usage of the timer:
Implementing the TimerTask interface, and that is the unit task, our single run business logic is written here
Instantiate a Timer object to start the TimerTask task and set the execution time and frequency of the task by invoking different methods in the actual application, the timer is used in the nightly processing time and the data state is stable when some background operations, such as data statistics, data backup and so on.
To perform a timed task using a timer