0

我正在尝试每隔 x 次执行一个 TimerTask ,并且与任务时间执行无关。我尝试了很多东西,我停在这里:

new Timer().schedule(new Send(),new Date();
...
Class Send extends TimerTask
{
    boolean shouldRun = true;
    public void run()
    {
            long start = System.currentTimeMillis();
            while(shouldRun)
            {
                    if(condition)
                            //send to db
                    long next = start + 300000;
                    try{
                        Thread.sleep(next - System.currentTimeMillis());
                        start = next;
                        }catch(InterruptedException e){
                            System.out.println(e);
                        }
            }
    }
}

正如你所看到的,在我发送到 db 之前我有一个条件,所以有时我不会做任何事情,所以我的记录时间应该是 5 分钟的跳跃。

这是输出: 15:08 15:22 15:40 前2次是假的,为什么?

我标记android的原因是因为我是在android系统上做的,也许它有一些效果。

4

1 回答 1

2

您应该使用 scheduleAtFixedRate,而不是像这样在 run 方法中睡觉。这将确保您的任务以固定的时间间隔(大约每 30 秒)运行,而不管任务执行需要多长时间。

new Timer().scheduleAtFixedRate(new Send(),new Date(),30000);
...
Class Send extends TimerTask
{
    boolean shouldRun = true;
    public void run()
    {
            long start = System.currentTimeMillis();
            while(shouldRun)
            {
                    if(condition)
                            //send to db                        
            }
    }
}
于 2013-01-30T15:13:20.460 回答