(Development support library) Timing scheduling

The main operation of the timer is to process timing tasks, just like an alarm clock that wakes up every day. There is support for timing tasks in Java, but the processing of such tasks only implements an interval trigger operation.

If you want to implement timing processing operations, you need to have a timing operation theme class and a timing task control, you can use two classes to achieve.

  • java.util.TimerTask class: implement timing task processing;
  • java.uitl.Timer class: start the task
  • Task start: public void scherdule(TimerTask tasl, long delay); the delay unit is milliseconds
  • 间隔触发:public  void   scheduleAtFixedRate​(TimerTask task, long delay, long period);

     task-the task to be scheduled.
            delay-the delay (in milliseconds) before executing the task.
            period-the time (in milliseconds) between consecutive task executions.

Example: Realize timing task processing

package 开发支持类库;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTask类 {
	public static void main(String[] args) {
		Timer timer = new Timer();	//定时任务
		//100秒后开始执行,每秒执行一次
		timer.scheduleAtFixedRate(new MyTask(), 100, 1000);
		timer.schedule(new MyTask(), 1000);	//延迟时间为0表示立即启动
	}
}

//任务主体
class MyTask extends TimerTask{

	@Override
	public void run() {
		//当前对象名字+当前时间
		System.out.println(Thread.currentThread().getName()+"定时任务执行,当前时间:"+System.currentTimeMillis());
	}
	
}

Timer-0 timing task execution, current time: 1610589612457
Timer-0 timing task execution, current time: 1610589613356
Timer-0 timing task execution, current time: 1610589613471

...
 

This kind of timing is supported by the most primitive way of JDK, but in fact, the timing processing code using this kind of way during development will be very complicated.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112599966