加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java:以随机间隔调度任务

发布时间:2020-12-15 02:53:34 所属栏目:Java 来源:网络整理
导读:我是 Java的新手,我正在尝试生成一个每5到10秒运行一次的任务,所以在5到10之间的任何时间间隔,包括10. 我尝试了几件事但到目前为止没有任何工作.我最近的努力如下: timer= new Timer();Random generator = new Random();int interval;//The task will run a
我是 Java的新手,我正在尝试生成一个每5到10秒运行一次的任务,所以在5到10之间的任何时间间隔,包括10.

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

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.我得到的是:

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

我从here了解到TimerTask无法重用,但我不知道如何修复它.顺便说一下,我的TimerTask非常复杂,至少持续1.5秒.

任何帮助将非常感谢,谢谢!

解决方法

尝试
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();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读