java - 定时器任务中的run方法执行了两次

标签 java timer

我创建了一个每 20 秒运行一次的计时器。计时器任务需要一分钟多才能完成任务。定时器任务中的 Run 方法在定时器任务完成前 20 秒后执行两次。

class A {

    static Timer timer; 

    TimerTask timertask = new TimerTask({
        public void run(){
            if(check for some data in the database before inserting )
            // Insert records into database 
        }
    }

    public test(){
        A.timer.scheduleAtFixedRate(imertask,0, 20*1000); 
    }
}

两条相同数据的记录插入数据库,时间差为14秒。我希望数据库中只有一条记录,非常感谢任何对此的帮助。

最佳答案

有意地,如果第一次执行时间超过 20 秒,第二次执行将立即开始。如果第一次执行时间超过 40 秒,第三次执行将在第二次执行后立即开始。依此类推,直到 N 秒后执行大约 N/20 次。

Documentation link

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

如果您两次插入相同的数据,那么问题似乎出在您如何决定是否已经插入该数据,而不是执行之间的间隔。

如果任务运行大约一分钟,这是否表明存在错误,或者只是需要多长时间(例如连接到远程数据库)?

关于java - 定时器任务中的run方法执行了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57403987/

相关文章:

java - 在此接口(interface)定义中,尖括号是什么意思?

java - 如何从 Android 中的 Google Fit 服务检索健康数据

c++ - C/C++ 经过的进程周期,不包括在断点处

javascript - ajax/JS 定时倒计时?

c - PIC16F883 定时器不工作

java - 在 Java 中结合两个具有透明度的颜色整数

java - Android - 在 View 中显示带有自定义文本的 fragment

c# - 如何防止 Global.asax 中的计时器加倍?

javascript - 多页倒数计时器

java - 在给定秒数后中断 HTTP 请求