Can you execute a task repeatedly in Java?

落花浮王杯 提交于 2020-01-03 03:31:24

问题


Is it possible to repeatedly execute a task each day, each minute, each second, each year? I want it to run like a daemon.

I need a scheduled task to search the database continuously; if it finds a certain value then it should execute a further task.


回答1:


I want to ask whether it is possible to repeatedly

You can use a loop, or a ScheduleExecutorService, or a Timer, or Quartz.

each day each minute each second each year

So once a second.

I want it to run like a daemon.

I would just make it a daemon thread then. No need to make it "like" a daemon.

if it find the correct value then it should do the remaining task.

Simple enough.

Read the data, check the value and if its what you want do the rest.




回答2:


The java.util.Timer and java.util.TimerTask classes, which I’ll refer to collectively as the Java timer framework, make it easy for programmers to schedule simple tasks.

public class Reminder {
    Timer timer;

    public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    }

    class RemindTask extends TimerTask {
        public void run() {
            System.out.format("Time's up!%n");
            timer.cancel(); //Terminate the timer thread
        }
    }



    public static void main(String args[]) {
        new Reminder(5);
        System.out.format("Task scheduled.%n");
    }
}

OR Scheduling a Timer Task to Run Repeatedly

int delay = 5000;   // delay for 5 sec.
int period = 1000;  // repeat every sec.
Timer timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            // Task here ...
        }
    }, delay, period);



回答3:


In order to do tasks based on time you would want to use threads. Check out this link in order to learn more about them: http://docs.oracle.com/javase/tutorial/essential/concurrency/threads.html




回答4:


Hmm so the program is going to be running all the time? Might want to look into Java Timer




回答5:


Perhaps a look at the java.util.Timer or Quartz Scheduler would be helpful.

A ScheduledThreadPoolExecutor might also be helpful. Look into their example code and you should be able to do it.



来源:https://stackoverflow.com/questions/11912659/can-you-execute-a-task-repeatedly-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!