gpt4 book ai didi

java - 每小时运行一次java函数

转载 作者:搜寻专家 更新时间:2023-10-31 08:10:51 28 4
gpt4 key购买 nike

我想每小时运行一个函数,通过电子邮件向用户发送他们进度的每小时屏幕截图。我在一个名为 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();

}

最佳答案

使用 ScheduledExecutorService :

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

优先使用 ScheduledExecutorService 而不是 Timer: Java Timer vs ExecutorService?

关于java - 每小时运行一次java函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32228345/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com