Java - 在特定日期执行方法

发布于 2024-10-04 09:07:32 字数 1566 浏览 0 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

寂寞美少年 2024-10-11 09:07:32

按优先顺序排列:

  1. Quartz 库(强烈推荐)。

  2. java.util.Timer。不如 Quartz 强大,但适合简单的工作。

  3. EJB 计时器服务。它的文档很少,它需要一个完整的 Java EE 容器,而且它实际上并没有做任何 Quartz 没有做的事情。

In order of preference:

  1. The Quartz library (highly recommended).

  2. java.util.Timer. Not as powerful as Quartz, but good for simple jobs.

  3. The EJB timer service. It's poorly documented, it requires a full Java EE container, and it doesn't really do anything that Quartz doesn't.

陪我终i 2024-10-11 09:07:32

查看 Timer 类

方法:

scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 
          Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

会让你做你想做的事。只要确保您使用的是正确的日期即可。

查看 API,您需要定义一个重载 run() 方法的 TimerTask。 run() 方法将包含您要调用的方法。

Check out the Timer Class

The method:

scheduleAtFixedRate(TimerTask task, Date firstTime, long period) 
          Schedules the specified task for repeated fixed-rate execution, beginning at the specified time.

will allow you to do what you want. Just be sure you are using the correct date.

Looking at the API, you will need to define a TimerTask that overloads the run() method. The run() method will contain the method you want to call.

不奢求什么 2024-10-11 09:07:32

如果你需要更健壮的东西,你也可以使用 Quartz 进行 Cron 之类的调度

If you need something more robust, you can also use Quartz for Cron like scheduling

苍白女子 2024-10-11 09:07:32

这将获取当前日期和时间。

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

private String getDateTime() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    return dateFormat.format(date);
}

然后创建一个循环,每秒检查该函数,并使用 if 语句来执行您想要的代码,如果时间是您想要的时间。

This will get the current date and time.

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

private String getDateTime() {
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    return dateFormat.format(date);
}

Then make a loop that checks the function every second and use an if statement to execute the code you want if the time is the time you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文