当前位置:网站首页>Eureka's timedsupersortask class (periodic task with automatic interval adjustment)
Eureka's timedsupersortask class (periodic task with automatic interval adjustment)
2022-06-21 08:05:00 【InfoQ】
Welcome to visit mine GitHub
cause
- One is based on Spring Cloud Application of framework , If registered to Eureka server, Then it will update the service list regularly , The code to start this scheduled task is in com.netflix.discovery.DiscoveryClient Class initScheduledTasks In the method , as follows ( From Engineering eureka-client, edition 1.7.0):
private void initScheduledTasks() {
// Update service list
if (clientConfig.shouldFetchRegistry()) {
// registry cache refresh timer
int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds();
int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
scheduler.schedule(
new TimedSupervisorTask(
"cacheRefresh",
scheduler,
cacheRefreshExecutor,
registryFetchIntervalSeconds,
TimeUnit.SECONDS,
expBackOffBound,
new CacheRefreshThread()
),
registryFetchIntervalSeconds, TimeUnit.SECONDS);
}
...
// Leave out the rest of the code
- In the above code ,scheduler yes ScheduledExecutorService Interface implementation , Its schedule MethodicalOfficial documentsAs shown below :

- The red box above shows : This method createsOne time task, But in actual tests , If in CacheRefreshThread Class run Method , You will find that this method will be called periodically ;
- So the question arises : Methodschedule(Callable<V> callable,long delay,TimeUnit unit)The creation is clearly aOne time task, but CacheRefreshThread ByPeriodic execution;
To find the answer
- The open run Method source code , Please pay attention to the following Chinese Notes :
public void run() {
Future future = null;
try {
// Use Future, You can set the timeout for the child thread , In this way, the current thread does not have to wait infinitely
future = executor.submit(task);
threadPoolLevelGauge.set((long) executor.getActiveCount());
// Specifies the maximum time to wait for a child thread
future.get(timeoutMillis, TimeUnit.MILLISECONDS); // block until done or timeout
//delay Is a very useful variable , We'll use that later , Remember here that every successful mission will delay Reset
delay.set(timeoutMillis);
threadPoolLevelGauge.set((long) executor.getActiveCount());
} catch (TimeoutException e) {
logger.error("task supervisor timed out", e);
timeoutCounter.increment();
long currentDelay = delay.get();
// When the task thread times out , Just put delay Double the variable , But it will not exceed the maximum delay time set during external call
long newDelay = Math.min(maxDelay, currentDelay * 2);
// Set to the latest value , Consider multithreading , So use the CAS
delay.compareAndSet(currentDelay, newDelay);
} catch (RejectedExecutionException e) {
// Once the blocking queue of the thread pool is full of pending tasks , A rejection policy was triggered , Will stop the scheduler
if (executor.isShutdown() || scheduler.isShutdown()) {
logger.warn("task supervisor shutting down, reject the task", e);
} else {
logger.error("task supervisor rejected the task", e);
}
rejectedCounter.increment();
} catch (Throwable e) {
// Once an unknown exception occurs , Stop the dispatcher
if (executor.isShutdown() || scheduler.isShutdown()) {
logger.warn("task supervisor shutting down, can't accept the task");
} else {
logger.error("task supervisor threw an exception", e);
}
throwableCounter.increment();
} finally {
// Here the mission is either done , Or something goes wrong , Use both cancel Methods to clean up tasks ;
if (future != null) {
future.cancel(true);
}
// As long as the scheduler doesn't stop , Then specify the waiting time and perform the same task again
if (!scheduler.isShutdown()) {
// Here's the reason for periodic tasks : As long as the scheduler is not stopped , Then create a one-time task , When the execution time is dealy Value ,
// Suppose that the timeout passed in during an external call is 30 second ( Input parameters of construction method timeout), The maximum interval time is 50 second ( Input parameters of construction method expBackOffBound)
// If the last task did not time out , Then in 30 Start a new mission in seconds ,
// If the last task timed out , Then in 50 Start a new mission in seconds ( There is a double operation in exception handling , Multiply by two 60 Seconds exceeded the maximum interval 50 second )
scheduler.schedule(this, delay.get(), TimeUnit.MILLISECONDS);
}
}
}
- The truth is in the last line of code above :scheduler.schedule(this, delay.get(), TimeUnit.MILLISECONDS): After performing the task , Will call... Again schedule Method , Perform the same task after a specified time , This interval depends on whether the last task timed out , If it goes out of time, the interval will be larger ;
- Summary : On the whole ,TimedSupervisorTask It's a periodic task at regular intervals , Once the timeout occurs, the interval time of the next cycle will be increased , If you continuously time out , So every time the interval is doubled , Until it reaches the upper limit set by the external parameters , Once the new task no longer times out , The interval time will automatically return to the initial value , And then there is CAS To control multithreading synchronization , Simple code , Ingenious design , It's worth learning ;
Welcome to your attention InfoQ: Xinchen, programmer
边栏推荐
- Yyds dry goods inventory junit5 learning 3: assertions class
- Blue Bridge Cup: Candy
- Mongodb installation (Graphic tutorial)
- Wechat official account docking: push article information to official account with one click
- (greedy) B. avoid local maximums
- Antique typesetting (20 points) (test point 4)
- Rdkit | compound library based on murcko skeleton clustering
- Ansa secondary development - external programs use socket to communicate with ansa
- Send using queue mailbox
- 为什呢代码没报错但是数据库里边的数据显示不出来
猜你喜欢

Le Code est correct, mais les données de la base de données ne sont pas affichées.

What is the MySQL database zipper table

Eureka的TimedSupervisorTask类(自动调节间隔的周期性任务)

Horizontal slot, one line of code can directly convert the web page to PDF and save it (pdfkit)

showCTF Web入门题系列

Is the index of nine interview sites of ten companies invalid?

2021-06-16 STM32F103 EXTI 中斷識別 使用固件庫

How can we make millions a year now?
![[visualization - source code reading] antvis / g-base interpretation - 1](/img/a6/411621e180fa717f98136ddfdbe673.jpg)
[visualization - source code reading] antvis / g-base interpretation - 1

Arduino about software uninstallation and library uninstallation
随机推荐
Yyds dry goods inventory rapid establishment of CEPH cluster
文件下载 二进制流的形式构造url和base64下载
Figure neural network and cognitive reasoning - Tang Jie - Tsinghua University
数字孪生实际应用案例-煤矿篇
2021-07-28 STM32F103 I2C Hardware Transfer Include previous IO Clock EXIT USB use firmware library
2021-06-16 STM32F103 exti interrupt identification using firmware library
Arduino about software uninstallation and library uninstallation
1005 Spell It Right (20 分)(测试点3)
There was a GC failure in the online go service. I was in a hurry
unity里现实摄像头运镜并LookAt到物体前方 基于Dotween
What are the differences between SQL and MySQL
Leetcode topic [array] -40- combined sum II
How to solve the problem that MySQL is not an internal command
解决Jenkins升级后不能保存配置的问题
A table to easily understand the prefix and suffix of increment and decrement operators
2021-06-16 STM32F103 EXTI 中斷識別 使用固件庫
Matlab 3D diagram (unconventional)
Global and Chinese market for packed gas chromatographic columns 2022-2028: Research Report on technology, participants, trends, market size and share
(对于换行符)gets和fgets的区别,puts和fputs的区别
Antique typesetting (20 points) (test point 4)