Java:以随机间隔安排任务 [英] Java: Scheduling a task in random intervals

查看:37
本文介绍了Java:以随机间隔安排任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 很陌生,我正在尝试生成一个每 5 到 10 秒运行一次的任务,因此在 5 到 10 之间的区域内的任何时间间隔,包括 10.

I am quite new to Java and I'm trying to generate a task that will run every 5 to 10 seconds, so at any interval in the area between 5 to 10, including 10.

我尝试了几件事,但到目前为止没有任何效果.我最近的努力如下:

I tried several things but nothing is working so far. My latest effort is below:

timer= new Timer();
Random generator = new Random();
int interval;

//The task will run after 10 seconds for the first time:
timer.schedule(task, 10000); 

//Wait for the first execution of the task to finish:               
try {
    sleep(10000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}

//Afterwards, run it every 5 to 10 seconds, until a condition becomes true:
while(!some_condition)){
    interval = (generator.nextInt(6)+5)*1000;
    timer.schedule(task,interval);

    try {
        sleep(interval);
    } catch(InterruptedException ex) {
    ex.printStackTrace();
    }
}

任务"是一个 TimerTask.我得到的是:

"task" is a TimerTask. What I get is:

Exception in thread "Thread-4" java.lang.IllegalStateException: Task already scheduled or cancelled

我从 此处 了解到 TimerTask 无法重用,但我不确定如何修复它.顺便说一下,我的 TimerTask 非常精细,至少持续 1.5 秒.

I understand from here that a TimerTask cannot be reused, but I am not sure how to fix it. By the way the my TimerTask is quite elaborate and lasts itself at least 1,5 seconds.

任何帮助将不胜感激,谢谢!

Any help will be really appreciated, thanks!

推荐答案

try

public class Test1 {
    static Timer timer = new Timer();

    static class Task extends TimerTask {
        @Override
        public void run() {
            int delay = (5 + new Random().nextInt(5)) * 1000;
            timer.schedule(new Task(), delay);
            System.out.println(new Date());
        }

    }

    public static void main(String[] args) throws Exception {
        new Task().run();
    }
}

这篇关于Java:以随机间隔安排任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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