We have seen a lot of timing functions on mobile phones, such as cleaning garbage, alarm clocks, etc. The timing functions mainly use Timer objects in Java, and it uses multi-threading technology internally.
The Time class is mainly responsible for completing timed planning tasks, which is to execute a task at a specified time.
The function of the Timer class is to set up scheduled tasks, and the class that encapsulates the content of the task is the TimerTask class. This class is an abstract class, and inheritance requires the implementation of a run method.
It is relatively simple to use Java to make timers, and it has ready-made interfaces to help implement it. In Java, timer and TimerTask are used to make timers, which are util packages. The java.util.Timer timer is actually a thread that schedules the TimerTasks owned by timed scheduling. A TimerTask is actually a class with a run method. The code that needs to be executed regularly is placed in the body of the run method. TimerTask is generally created in an anonymous class.
java.util.Timer timer = new java.util.Timer(true);// true means that this timer is run in daemon mode (low priority, // The timer ends at the end of the program, and it also ends automatically). Note that javax.swing // There is also a Timer class in the package. If the swing package is used in the import, // Pay attention to the name conflict. TimerTask task = new TimerTask() {public void run() {... //Put the code that needs to be executed every time here. }};//The following are several methods for scheduling tasks: timer.schedule(task, time);// time is Date type: executed once at a specified time. timer.schedule(task, firstTime, period);// firstTime is Date type, period is long // Starting from the firstTime moment, it is executed every milliseconds of the period. timer.schedule(task, delay) // delay is type long: execute timer.schedule(task, delay, period) // delay is long, period is long: after delay milliseconds, execute every period // milliseconds.In our actual application, the more commonly used thing is to separate TimerTask and form a custom task by a separate class.
import java.util.Timer;public class TimerTaskTest extends java.util.TimerTask{@Override public void run() {// TODO Auto-generated method stub System.out.println("start");}} import java.util.Timer;public class Test {public static void main(String[] args){Timer timer = new Timer();timer.schedule(new TimerTaskTest(), 1000, 2000);}}Summarize
The above is all about Java implementation of a simple timer code parsing, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!