java - 在给定的时间开始预定的 Activity ?

标签 java scheduled-tasks

我正在编写一个基于 Java 的 shell 类型...呃...东西。无论如何,我正在实现的命令之一是 schedule 命令,您可以在其中告诉它您想要运行命令的时间,它会等待时间,运行命令一次,然后退出。但是,我无法弄清楚如何让它检查时间 - 我实现了一个只检查日期是否相等的方法,做了一些研究以查看是否存在更好的解决方案,然后发现显然 Date 不是好用的东西。我该怎么办?

MCVE:

import java.util.Date;

public class Scheduler extends Thread {
    private Date goAt;
    private String command;
    public Scheduler(Date goAt, String command) {
        this.goAt = goAt;
        this.command = command;
    }
    public void start() {
        super.start();
    }
    public void run() {
        while (!goAt.equals(new Date())) {} //Wait until the dates are equal
        runCommand(command); //In the real thing, this runs the command.
    }
    public void runCommand(String command) {
        System.out.println("Command: " + command);
    }
    public static void main(String[] args) {
        Scheduler task = new Scheduler(new Date(System.currentTimeMillis() + 5000));
        task.start();
    }
}

我希望在不使用第三方库或必须单独下载的库的情况下完成此操作。如果没有办法这样做,那么我会接受第三方库的答案,但优先考虑没有它们的解决方案。同样理想的是,如果答案允许我直接指定运行命令的时间,而不是计算相对时间差并使用它。

最佳答案

使用the builtin java.util.Timer class安排代码在给定的 future 时间或在给定的延迟后运行。

关于java - 在给定的时间开始预定的 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16463835/

相关文章:

java - '这个方法必须返回 int 类型的结果' Java?

c++ - 如何在每 1 分钟后在 C++ 中执行特定代码

linux - 更改进程的 nice 值在 Linux 中无效

安装Tomcat 8后Java导入util.Arrays失败,如何解决?

java - 可以通过uid获取好友列表吗?

java - java中处理大量异步调用

sql - 如何调度存储过程?

flutter - Flutter/Dart-安排Mysql查询每隔几分钟运行一次?

java - 如何使用java处理缓存(ConcurrentHashMap)中的锁

java - 使用子类 SpinnerListModel 在 JSpinner 中键入数字