在Java中并发执行计划任务 [英] Concurrent execution of scheduled tasks in Java

查看:448
本文介绍了在Java中并发执行计划任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TimerTask ,用于在特定时间间隔收集指标。但是,任务执行的时间段可能少于任务执行的时间(有时如果某些事件超时并被延迟)。

I have a TimerTask that is designed to gather metrics at a specific interval. However it is possible that the period of the task execution is less than the time of task execution (occasionally if something times out and gets delayed).

有办法

我知道Timer使用单个线程,并且 ScheduledThreadPoolExecutor

I know that Timer uses a single thread, and the ScheduledThreadPoolExecutor will delay execution regardless of the rate.

推荐答案

我建议你使用 Executors.newCachedThreadPool() newCachedThreadPool(ThreadFactory threadFactory)工厂,结合计时器。所以代码应该像这样

I would recommend you using Executors.newCachedThreadPool() or newCachedThreadPool(ThreadFactory threadFactory) with your own thread factory, in conjuction with Timer. So the code should look like this

Executor executor = Executors.newCachedThreadPool();
Timer time = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

    public void run() {
        executor.execute(new Runnable() {

             public void run() {
                  //your business logic
             }
        });
    }
}, delay, period);

这样,您可以安排某些时间段的任务,并且它们都会同时运行。

This way you would schedule tasks with some period and they would all run concurrently.

这篇关于在Java中并发执行计划任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆