Java中定时任务的并发执行 [英] Concurrent execution of scheduled tasks in Java

查看:37
本文介绍了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).

有没有一种方法可以同时执行多个 TimerTask 或 Runnables、线程等,而无需等待前一个任务完成?

Is there a way to execute multiple TimerTasks or Runnables, threads, etc. concurrently without waiting for the previous task to complete?

我知道 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天全站免登陆