[Original] timer and system time, Timer System
Problem:
--------------------------------------------------------------------------------
User feedbackEnabling scheduled activities in advance or later
1) log on to the server and check whether the time is slow or fast. In short, there are several servers with inaccurate time.
2) check that the code is ScheduledExecutorService.ScheduleAtFixedRateJava API, there is no Bug here
3) Check the log4j log output and find:
For a scheduled activity at, the previous [running time of the activity] is 12 o'clock. For the next few days, the [running time of the activity] is, and the interval is the same.
Confirm,The server time is synchronized between the changes, but the jvm is not restarted.
4)It is initially suspected that the internal execution of ScheduledExecutorService uses relative time, not the system time of each sampling server.
Confirm the problem-test:
--------------------------------------------------------------------------------
5) test
ScheduledExecutorService service = Executors. newScheduledThreadPool (2); service. scheduleAtFixedRate (new Runnable () {// Runnable-1 @ Override public void run () {System. out. println (String. format ("\ n ##### % s ####", new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss. S "). format (new Date () ;}}, 0, 10, TimeUnit. SECONDS); // executes the service once every 10 SECONDS. scheduleAtFixedRate (new Runnable () {// Runnable-2 int I = 0; @ Override public void run () {System. out. print (I ++) + ",") ;}, 0, 1, TimeUnit. SECONDS); // one second
Output-1:
0,
#### 16:51:48. 118 ####
1, 2, 3, 4, 5, 6, 7, 8, 9,
#### 16:51:58. 93 ####
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
#### 16:52:08. 94 ####
, 22, 26, 29,
####16:52:18. 93####
30,31, 32,33, 34,35, 36,37, 38,39,
####16:52:28. 93####
,
####16:58:36. 480#### // Adjust the time
50, 51,
####16:58:46. 480####
60, 61, 64, 65, 68, 69,
#### 16:58:56. 480 ####
At 16:52:28. 93 adjusted the time To 16:58:36. 480 (backward hop), Runnable-2 still made 10 output, then Runnable-1 output 1 time
Output-2:
0,
#### 17:12:40. 971 ####
1, 2, 3, 4, 5, 6, 7, 8, 9,
####17:12:50. 943####
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
####17:13:00. 943#### // Adjust the time
20, 21, 24, 25, 26, 27, 28, 29,
####17:05:09. 69####
30,31, 32,33, 34,35, 36,37, 38,39,
####17:05:19. 68####
At 17:13:00. 943, adjust the time To 17:05:09. 69 (forward), The Runnable-2 still made 10 output, then the Runnable-1 output 1 time
Test conclusion: the time skip does not affect the Runnable-1 output once every 10 seconds, ScheduledExecutorService does not use the system time
Problem confirmation-JDK source code:
--------------------------------------------------------------------------------
Initialization
ScheduledExecutorService service = Executors.newScheduledThreadPool(2); new ScheduledThreadPoolExecutor(corePoolSize) super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS, new DelayedWorkQueue())
Register a scheduled task
service.scheduleAtFixedRate(new Runnable() {...}) RunnableScheduledFuture<?> t = decorateTask(command, new ScheduledFutureTask<Object>(command, null, triggerTime(initialDelay, unit), unit.toNanos(period))); // ScheduledThreadPoolExecutor.ScheduledFutureTask delayedExecute(t); prestartCoreThread addIfUnderCorePoolSize addThread Worker w = new Worker(firstTask); // ThreadPoolExecutor.Worker Thread t = threadFactory.newThread(w); workers.add(w); super.getQueue().add(command); // DelayedWorkQueue
Run
ThreadPoolExecutor.Worker.run task = getTask() r = workQueue.take(); // DelayedWorkQueueScheduledThreadPoolExecutor.DelayedWorkQueue.take dq.take(); // DelayQueue<RunnableScheduledFuture>
DelayQueue <E extends Delayed>
An unbounded blocking queue of Delayed elements, which can be extracted only when the delay expires. The queue header is the Delayed element with the longest storage time after the delay expires. If the delay has not expired, the queue has no header and poll returns null. When the getDelay (TimeUnit. NANOSECONDS) method of an element returns a value less than or equal to 0, it will expire. Even if you cannot use take or poll to remove unexpired elements, these elements are not treated as normal elements. For example, the size method returns both the number of expired and unexpired elements. The queue does not allow null elements. Take () long delay = first. getDelay (TimeUnit. NANOSECONDS); if (delay> 0) {long tl = available. awaitNanos (delay );}
ScheduledThreadPoolExecutor. ScheduledFutureTask. getDelay
Public long getDelay (TimeUnit unit) {return unit. convert (time-now (), TimeUnit. NANOSECONDS);} final long now () {/*** public static long nanoTime () * returns the current value of the most accurate available system timer, in milliseconds. * This method can only be used to measure the time that has elapsed, regardless of any other time concept of the system or clock time. * The return value indicates the number of milliseconds counted from a fixed period of time (or from a later period, so this value may be negative ). */Return System. nanoTime ()-NANO_ORIGIN ;}
Confirm the problem-nanoTime test:
--------------------------------------------------------------------------------
New Thread () {public void run () {long lastNanos = System. nanoTime (); long lastMilis = System. currentTimeMillis (); for (int I = 0; I <100; I ++) {try {Thread. sleep (Limit L);} catch (InterruptedException e) {}// output one time in 10 seconds long nanos = System. nanoTime (); long millis = System. currentTimeMillis (); System. out. println (String. format ("%-25 s %-10 s % s-% s = % s [% s]", new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss. S "). format (new Date (millis), millis-lastMilis, nanos, lastNanos, nanos-lastNanos, (nanos-lastNanos)/1000/1000); lastNanos = nanos; lastMilis = millis ;}}}. start ();
Output:
10:10:45. 950 10001 107273041687944-107263041775958 = 9999911986 [9999]
10:10:55. 997 10047 107283088127723-107273041687944 = 10046439779 [10046]
10:20:04. 198548201107293088578057-107283088127723 = 10000450334 [10000]
10:00:12. 399-1191799107303089035855-107293088578057 = 10000457798 [10000]
10:00:22. 399 10000 107313089495208-107303089035855 = 10000459353 [10000]
At 10:10:55. 997, the adjustment time is 10:20:04. 198 (Backward Jump), and at 10:20:04. 198, the adjustment time is 10:00:12. 399 (Forward jump ),
Nanos-lastNanos is always maintained at around 10 s, and millis-lastMilis indeed the expected time
Thoughts and goals:
--------------------------------------------------------------------------------
7) I want to create a timer that depends on the timer of the current system time. By the way, the current problem is solved.
A) It is not a scheduled task, not a task system.
B) it only does one thing and reminds me to do a task at the time.
For example, after, I am reminded that it is time to eat chicken. After, it is time to fight.
Preliminary Design:
--------------------------------------------------------------------------------
8) Preliminary Design
A) First, create a task thread pool to execute the timer wake-up task.
Executors. newScheduledThreadPool (workServicePoolSize)
B) Create a timer thread and execute handleFunc every one second (Heartbeat step: 1 second)
Executors. newSingleThreadScheduledExecutor
C) handleFunc places the tasks found in the current system time in the task thread pool for execution by the task thread pool.
Execute (new Runnable (){});
It can initially solve the problem of task execution relying on system time.
Detailed Design:
--------------------------------------------------------------------------------
9) The Linux system will get faster or slower, for example, the combat force ranking deadline and start to receive rewards in 30 minutes.
A) if the speed is too high, everyone is at, but the server is already at, and the brothers who want to wait for the final rush will immediately cry.
B) if it is too slow, everyone is at, but the server is at. I have all rested and are ready to get the rewards. You will be able to hit the combat force list.
A) after each handleFunc execution, record the current execution time as lastExecuteTime
B) handleFunc: Compare executeTime with lastExecuteTime IN THE NEXT execution.
If executeTime = lastExecuteTime + 1: (Heartbeat Step 1 s)
Normal time, normal execution
If executeTime> lastExecuteTime + 1:
The time is faster (the server time is usually slow; the server time is corrected and the server time is fast forward). You need to handle the following:
[LastExecuteTime + 1, executeTime-1] The task depends on the business needs to be completed immediately
The [executeTime] task is a normal task at the current time and needs to be executed normally.
If executeTime <= lastExecuteTime:
The time is slow (usually the server time is fast; the server time will be rolled back when the server time is corrected ):
[ExecuteTime, lastExecuteTime] has been executed. Generally, it does not need to be executed again.
NOTE 1: The current time and lastExecuteTime are erased in milliseconds. The daily scheduled service is sufficient for second-based calculation.
Note 2: The server can synchronize time once every one hour. For example, NN: 38 usually avoids the entire point, half point, and entire very
Note 3: The maximum error is several seconds for hourly synchronization. for common services:
When the time is getting faster, you can immediately execute the task. There is not much difference between the important rewards in advance or the delay of 5 seconds.
When the time is slow, you can ignore the tasks between [executeTime, lastExecuteTime] and do not need to execute them again.
Note 4: the execution time granularity is relatively small. For example, if the execution time is one second, the time skip issue can be ignored.
Detailed design-scheduled task:
--------------------------------------------------------------------------------
10) the timer solution can solve the time jump problem. However, daily development is usually a scheduled periodic task.
For example, you can call a rooster at and a timer at. However, you can call a rooster at every day. This is a scheduled periodic task that requires 12 o'clock every day.
Notify me to eat it. The solution can be as follows:
A) Modify handleFunc to find the task based on the current system time"
B) The task warehouse to be searched is divided into two types:
One-time task warehouse:
Execute the task and remove the task. The key stored in the task warehouse is the task execution timestamp.
Daily task Repository:
The key stored in the task warehouse is the number of seconds for the task relative to 00:00:00 in the morning.
During handleFunc execution, check how many seconds have passed today (this is the system time), find the corresponding task, and then execute it. This does not need to remove the task.
This is still the concept of a timer,"It's time from. I told you to eat the chicken. It's time from tomorrow. I'll ask you to eat the chicken again.",
Instead of "12 o'clock, I told you to eat chicken, and then I told you to eat chicken 24 hours later ".
NOTE 1: In the same way, task warehouses can be added every week, every hour, or every minute.
NOTE 2: You do not need to perform tasks every month, every year, or every ten years.
Note 3: The handleFunc runs directly once it passes (each interval is one second calculated by nano, so it should be executed)
Interface Design:
--------------------------------------------------------------------------------
11) external interface:
A) Start
B) Disable
C) register a one-time task
D) register a weekly task
E) register daily tasks
F) register a task at a time: the number of minutes and seconds of each hour.
G) register each task
H) Register tasks per second
Other Instructions:
--------------------------------------------------------------------------------
12) Others:
A) handleFunc only finds the task and throws it into the worker thread pool for execution. It does not occupy much CPU and will not cause task selection congestion.
B) handleFunc will go to the task warehouse every minute to find and execute suitable tasks. If the same task is not executed for one minute, the current task will continue to be executed without delay and will be executed at the same time.
Since the task is a task per minute, the task should not be more than 1 minute. If the task occasionally exceeds 1 minute, you can lock it in the registered task.
C) The server time is slow. When the server time is corrected, the server time will be fast forward, and the completion task will only be supplemented for a certain period of time (such as 30 minutes)
The system time is one-hour synchronization, with the maximum error of only a few seconds. If the system time is large, you should upgrade the kernel or change the server.
The duration of completion may affect normal services (normal service processes, system resource usage, etc)
D) when a task is thrown into the thread pool, it will catch it to prevent the current thread from being hung.