每天在固定时间运行 Java 方法 [英] Running a Java method at a set time each day

查看:35
本文介绍了每天在固定时间运行 Java 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 还比较陌生,我已经开始着手一个项目.但是,我遇到了一个块.我需要一种在一天中的特定时间运行的方法.我已经做了很多搜索,但我找不到任何似乎可以解决问题的东西.我遇到了 Timer 类,但它似乎以特定的时间间隔运行.Scheduler 类似乎也有同样的问题.我也遇到过 Quartz,但我认为我需要更轻量级的东西,而且我只能看到如何每隔一段时间做事.

I'm relatively new to Java and I've pick up a project to work on. However, I've run into a block. I need a method to run at a certain times throughout the day. I've done quite a bit of searching but I can't find anything that seems like it would do the trick. I've run into the Timer class but it appears to run at certain intervals. The Scheduler class, appeared to have the same issue. I also came across Quartz but I think I need something more lightweight and I could only see how to do things at intervals.

也许,只是因为我是新手,我错过了一些可以在这些课程中帮助我的东西,但我真的被困住了,可以使用一些帮助.

Perhaps, just because I'm new, I've missed some things that could help me in these classes, but I'm really stuck and could use some help.

如果有人能给我指点一个每天在特定时间运行的课程(能够取消活动的奖励积分),并告诉我如何正确使用该课程,那就太棒了!

If someone could point me to a class that will run something at a certain time of day, everyday (bonus points for being able to cancel the event), and show me how to correctly use the class, that would be awesome!

TL;DR:需要一个在一天中的某个时间做某事的类,而不是间隔一段时间,因为该程序可能会在一天中多次重新启动.

TL;DR: Need a class that does something at a time of day, not at an interval because the program may be restarted multiple times throughout the day.

推荐答案

试试 TimerTask 类

try the TimerTask class

欲了解更多信息,请查看http://oreilly.com/java/archive/quartz.html

for more info check out http://oreilly.com/java/archive/quartz.html

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ReportGenerator extends TimerTask {

  public void run() {
    System.out.println("Generating report");
    //TODO generate report
  }

}

class MainApplication {

  public static void main(String[] args) {
    Timer timer = new Timer();
    Calendar date = Calendar.getInstance();
    date.set(
      Calendar.DAY_OF_WEEK,
      Calendar.SUNDAY
    );
    date.set(Calendar.HOUR, 0);
    date.set(Calendar.MINUTE, 0);
    date.set(Calendar.SECOND, 0);
    date.set(Calendar.MILLISECOND, 0);
    // Schedule to run every Sunday in midnight
    timer.schedule(
      new ReportGenerator(),
      date.getTime(),
      1000 * 60 * 60 * 24 * 7
    );
  }//Main method ends
}//MainApplication ends

这篇关于每天在固定时间运行 Java 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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