我想每小时运行一次功能,向用户发送每小时进度的屏幕截图。我在名为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 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/