-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path77_Timer Task
More file actions
92 lines (78 loc) · 2.69 KB
/
77_Timer Task
File metadata and controls
92 lines (78 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
//Timer = A facility for threads to schedule task for future execution in a background thread
//TimerTask = A task that can be scheduled for one-time or repeated execution by a Timer
public class Main{
public static void main (String[] args){
Timer timer = new Timer();
TimerTask task = new TimerTask(){
@Override
public void run() {
System.out.println("Task is complete :)");
}
};
/*Case 1*/
//timer.schedule(task,0);//(task,time delay)
// >> Task in complete :) shown after 0s
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR,2020);
date.set(Calendar.MONTH,Calendar.JUNE);
date.set(Calendar.DAY_OF_MONTH,20);
date.set(Calendar.HOUR_OF_DAY,0);//0-24
date.set(Calendar.MINUTE,0);
date.set(Calendar.SECOND,0);
date.set(Calendar.MILLISECOND,0);
timer.schedule((task, date.getTime());
//>>Shown at 20 June 2022 00:00
-------schedule.AtFixedRate
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
//Timer = A facility for threads to schedule task for future execution in a background thread
//TimerTask = A task that can be scheduled for one-time or repeated execution by a Timer
public class Main{
public static void main (String[] args){
Timer timer = new Timer();
TimerTask task = new TimerTask(){
int counter = 10;
@Override
public void run() {
if(counter>0) {
System.out.println(counter + " seconds");
counter --;
}
else{
System.out.println("HAPPY NEW YEAR!");
timer.cancel();
}
}
};
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR,2020);
date.set(Calendar.MONTH,Calendar.DECEMBER);
date.set(Calendar.DAY_OF_MONTH,31);
date.set(Calendar.HOUR_OF_DAY,23);//0-24
date.set(Calendar.MINUTE,59);
date.set(Calendar.SECOND,50);
date.set(Calendar.MILLISECOND,0);
/*Case 3
timer.scheduleAtFixedRate(task,0,1000);//(task, firstTime [Time/delay of first instance], period [how often repeat])
>>
10 seconds
9 seconds
8 seconds
7 seconds
6 seconds
5 seconds
4 seconds
3 seconds
2 seconds
1 seconds
HAPPY NEW YEAR!
*/
//To execute at a specific date time
timer.scheduleAtFixedRate(task,date.getTime(),1000);
//>>Same result as Case 3, but occur at specific date time
}
}