Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

schedule - Run java function every hour

I want to run a function every hour, to email users a hourly screenshot of their progress. I code set up to do so in a function called sendScreenshot()

How can I run this timer in the background to call the function sendScreenshot() every hour, while the rest of the program is running?

Here is my code:

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();

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a ScheduledExecutorService:

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

Prefer using a ScheduledExecutorService over Timer: Java Timer vs ExecutorService?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...