每小时运行一次java函数

时间:2015-08-26 13:42:26

标签: java schedule

我希望每小时运行一次功能,向用户发送每小时的进度截图。我在一个名为sendScreenshot()

的函数中进行代码设置

如何在后台运行此计时器,每小时调用sendScreenshot()函数,而程序的其余部分正在运行?

这是我的代码:

public int onLoop() throws Exception{
    if(getLocalPlayer().getHealth() == 0){
        playerHasDied();
    }
    return Calculations.random(200, 300);

}

public void sendScreenShot() throws Exception{
    Robot robot = new Robot();
    BufferedImage screenshot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    screenshotNumber = getNewestScreenshot();
    fileName = new File("C:/Users/%username%/Dreambot/Screenshots/Screenshot" + screenshotNumber +".");
    ImageIO.write(screenshot, "JPEG", fileName);

    mail.setSubject("Your hourly progress on account " + accName);
    mail.setBody("Here is your hourly progress report on account " + accName +". Progress is attached in this mail.");
    mail.addAttachment(fileName.toString());
    mail.setTo(reciepents);
    mail.send();

}

4 个答案:

答案 0 :(得分:16)

使用ScheduledExecutorService

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        sendScreenShot();
    }
}, 0, 1, TimeUnit.HOURS);

首选使用ScheduledExecutorService而不是TimerJava Timer vs ExecutorService?

答案 1 :(得分:1)

根据this article by Oracle,也可以使用@Schedule注释:

@Schedule(hour = "*")
public void doSomething() {
    System.out.println("hello world");
}

例如,秒和分钟的值可以是0-59,小时0-23,月份1-12。

此处还介绍了其他选项。

答案 2 :(得分:0)

java的Timer在这里工作正常。

http://docs.oracle.com/javase/6/docs/api/java/util/Timer.html

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
    public void run() {
        // ...
    }
}, delay, 1 * 3600 * 1000); // 1 hour between calls

答案 3 :(得分:0)

对于这种类型的周期执行(意味着每天或每小时),您需要使用的是这样的Timer:

public static void main(String[] args) throws InterruptedException {
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 7);
        today.set(Calendar.MINUTE, 45);
        today.set(Calendar.SECOND, 0);

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("I am the timer");
            }
        };
//        timer.schedule(task, today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS)); // period: 1 day
        timer.schedule(task, today.getTime(), TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS)); // period: 5 seconds

    }

该示例将从当前日期和上午7:45起每5秒执行一次时间任务。 祝你好运。