Import Java.util.Calendar;
Import Java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;
public class Timetest {
public static void Main (string[] args) {
Timer1 ();
Timer2 ();
Timer3 ();
Timer4 ();
}
The first method: set the specified task tasks to execute schedule (timertask task, Date time) at specified times
public static void Timer1 () {
Timer timer = new timer ();
Timer.schedule (New TimerTask () {
public void Run () {
System.out.println ("-------set to specify task--------");
}
}, 2000);//Set the time specified, here is 2000 milliseconds
}
The second method: set the execution of a fixed delay peroid for the specified task tasks after specifying delay delays
Schedule (timertask task, long delay, long period)
public static void Timer2 () {
Timer timer = new timer ();
Timer.schedule (New TimerTask () {
public void Run () {
System.out.println ("-------set to specify task--------");
}
}, 1000, 5000);
}
The third method: Set the execution of the fixed frequency peroid of the specified task tasks after specifying the delayed delay.
Scheduleatfixedrate (timertask task, long delay, long period)
public static void Timer3 () {
Timer timer = new timer ();
Timer.scheduleatfixedrate (New TimerTask () {
public void Run () {
System.out.println ("-------set to specify task--------");
}
}, 1000, 2000);
}
Fourth method: Schedule the specified task to execute at a fixed rate period the specified time Firsttime begins to repeat.
Timer.scheduleatfixedrate (TimerTask task,date Firsttime,long period)
public static void Timer4 () {
Calendar calendar = Calendar.getinstance ();
Calendar.set (Calendar.hour_of_day, 12); Control time
Calendar.set (calendar.minute, 0); Control points
Calendar.set (Calendar.second, 0); Control seconds
Date time = Calendar.gettime (); The time to execute the task, here is today's 12:00:00
Timer timer = new timer ();
Timer.scheduleatfixedrate (New TimerTask () {
public void Run () {
System.out.println ("-------set to specify task--------");
}
}, time, 1000 * 60 * 60 * 24);//This setting will be delayed daily fixed execution
}
}
4 ways to use timers in Java