简体   繁体   English

Java:如何在指定时间仅运行此代码一次?

[英]Java: How to run this code only once at this specified time?

I'm trying to run a method once a week.我正在尝试每周运行一次方法。 For example, every Monday 8pm.例如,每周一晚上 8 点。 I use this code:我使用这个代码:

    Timer timer = new Timer();

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    calendar.set(Calendar.HOUR_OF_DAY, 20);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 00);
    Date time = calendar.getTime();

    timer.schedule(new PrintTask(),
            time);

    // other code where variable gets increased



public class PrintTask extends TimerTask {
    public void run() {

          variable = 0;
    }
}

However, if I am right, the dosomething code is run continuously - as long as the calendar time has already passed.但是,如果我是对的,那么dosomething代码就会连续运行 - 只要日历时间已经过去。 For example, now it has already been Monday, so the dosomething code is run all the time.例如,现在已经是星期一,所以一直在运行dosomething代码。 A variabele gets increased, but it must be reset to 0 on Monday.变量增加,但它必须在星期一重置为 0。 The variable is now constantly 0, because it is reset again and again.该变量现在始终为 0,因为它一次又一次地重置。 If I use calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);如果我使用calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); , the variable is not reset, because it has not been Sunday yet. ,变量没有被重置,因为还没有到星期天。 But as soon as it is Sunday 8pm, he will probably continue to reset the rest of that day.但是一旦到了周日晚上 8 点,他可能会继续重置当天剩余的时间。

I want the dosomething code to be executed only once at the one time specified.我希望dosomething代码在指定的时间只执行一次。 Can someone tell me how to adjust the code to achieve this?有人可以告诉我如何调整代码来实现这一目标吗?

Sorry for my English对不起我的英语不好

Please look at this question here( How i can run my TimerTask everyday 2 PM ).请在这里查看这个问题( 我如何每天下午 2 点运行我的 TimerTask )。 It almost deals with same kind of problem.它几乎处理相同类型的问题。

Cancel the timer using the cancel api of Timer class, and reschedule the timer inside the run () method;使用Timer类的cancel api取消定时器,在run ()方法内部重新调度定时器; this should prevent from updating the variable everytime.这应该可以防止每次更新变量。

The Timer class can be used to schedule things to run once, or multiple times. Timer 类可用于安排事物运行一次或多次。 The way you are scheduling it at this moment will only make it once at the given time.你现在安排它的方式只会在给定的时间做一次。

https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule(java.util.TimerTask,%20java.util.Date) https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html#schedule(java.util.TimerTask,%20java.util.Date)

There are better options if you want to schedule tasks, for example the ScheduledExecutorService:如果要安排任务,还有更好的选择,例如 ScheduledExecutorService:

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html

According to Java Concurrency in Practice:根据实践中的Java并发:

  1. Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't.计时器可能对系统时钟的变化敏感,而 ScheduledThreadPoolExecutor 则不然。
  2. Timer has only one execution thread, so long-running task can delay other tasks.定时器只有一个执行线程,所以长时间运行的任务可以延迟其他任务。 ScheduledThreadPoolExecutor can be configured with any number of threads. ScheduledThreadPoolExecutor 可以配置任意数量的线程。 Furthermore, you have full control over created threads, if you want (by providing ThreadFactory).此外,如果需要,您可以完全控制创建的线程(通过提供 ThreadFactory)。
  3. Runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... ie scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run. TimerTask 中抛出的运行时异常会杀死该线程,从而使 Timer 死掉 :-( ... 即计划任务将不再运行。ScheduledThreadExecutor 不仅可以捕获运行时异常,而且还可以让您根据需要处理它们(通过从ThreadPoolExecutor).抛出异常的任务将被取消,但其他任务将继续运行。

http://jcip.net/ http://jcip.net/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM