Jannik
Jannik

Reputation: 421

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

}

Upvotes: 6

Views: 25717

Answers (5)

Palmeta
Palmeta

Reputation: 61

while (true) {
        
        DateTime d = new DateTime();
        switch(d.getMinuteOfHour()) {
            
        case 56:
            runHourly();
            break;
            
        case 41:
            if(d.getHourOfDay() == 2) {
                runAt0241Daily();
            }
            break;
        }   
        SUM.wait(59000);
    }

How about this for something you can control and understand?

Upvotes: 0

For this type of period execution, meaning every day or every hour, all you need is using a Timer like this :

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

    }

this exemple will execute the timetask every 5 seconds from the current date and 7:45 am. Good Luck.

Upvotes: 0

Edwin Lambregts
Edwin Lambregts

Reputation: 408

According to this article by Oracle, it's also possible to use the @Schedule annotation:

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

For example, seconds and minutes can have values 0-59, hours 0-23, months 1-12.

Further options are also described there.

Upvotes: 2

twentylemon
twentylemon

Reputation: 1246

java's Timer works fine here.

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

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53859

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?

Upvotes: 23

Related Questions