How to schedule a periodic task in Java?

前端 未结 11 1617
星月不相逢
星月不相逢 2020-11-22 08:51

I need to schedule a task to run in at fixed interval of time. How can I do this with support of long intervals (for example on each 8 hours)?

I\'m currently using <

相关标签:
11条回答
  • 2020-11-22 09:01

    Use Google Guava AbstractScheduledService as given below:

    public class ScheduledExecutor extends AbstractScheduledService {
    
       @Override
       protected void runOneIteration() throws Exception {
          System.out.println("Executing....");
       }
    
       @Override
       protected Scheduler scheduler() {
            return Scheduler.newFixedRateSchedule(0, 3, TimeUnit.SECONDS);
       }
    
       @Override
       protected void startUp() {
           System.out.println("StartUp Activity....");
       }
    
    
       @Override
       protected void shutDown() {
           System.out.println("Shutdown Activity...");
       }
    
       public static void main(String[] args) throws InterruptedException {
           ScheduledExecutor se = new ScheduledExecutor();
           se.startAsync();
           Thread.sleep(15000);
           se.stopAsync();
       }
    }
    

    If you have more services like this, then registering all services in ServiceManager will be good as all services can be started and stopped together. Read here for more on ServiceManager.

    0 讨论(0)
  • 2020-11-22 09:06

    Do something every one second

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            //code
        }
    }, 0, 1000);
    
    0 讨论(0)
  • 2020-11-22 09:07

    Try this way ->

    Firstly create a class TimeTask that run your task, it looks like:

    public class CustomTask extends TimerTask  {
    
       public CustomTask(){
    
         //Constructor
    
       }
    
       public void run() {
           try {
    
             // Your task process
    
           } catch (Exception ex) {
               System.out.println("error running thread " + ex.getMessage());
           }
        }
    }
    

    then in main class you instantiate the task and run it periodically started by a specified date:

     public void runTask() {
    
            Calendar calendar = Calendar.getInstance();
            calendar.set(
               Calendar.DAY_OF_WEEK,
               Calendar.MONDAY
            );
            calendar.set(Calendar.HOUR_OF_DAY, 15);
            calendar.set(Calendar.MINUTE, 40);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
    
    
    
            Timer time = new Timer(); // Instantiate Timer Object
    
            // Start running the task on Monday at 15:40:00, period is set to 8 hours
            // if you want to run the task immediately, set the 2nd parameter to 0
            time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
    }
    
    0 讨论(0)
  • 2020-11-22 09:10

    my servlet contains this as a code how to keep this in scheduler if a user presses accept

    if(bt.equals("accept")) {
        ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
        String lat=request.getParameter("latlocation");
        String lng=request.getParameter("lnglocation");
        requestingclass.updatelocation(lat,lng);
    }
    
    0 讨论(0)
  • 2020-11-22 09:13

    You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time

    0 讨论(0)
  • 2020-11-22 09:13

    If you want to stick with java.util.Timer, you can use it to schedule at large time intervals. You simply pass in the period you are shooting for. Check the documentation here.

    0 讨论(0)
提交回复
热议问题