[java] Java에서 주기적 작업을 예약하는 방법은 무엇입니까?

정해진 시간 간격으로 작업을 실행하도록 예약해야합니다. 긴 간격 (예 : 8 시간마다)을 지원하여이 작업을 수행하려면 어떻게해야합니까?

현재을 사용하고 java.util.Timer.scheduleAtFixedRate있습니다. java.util.Timer.scheduleAtFixedRate오랜 시간 간격을 지원 합니까 ?



답변

ScheduledExecutorService를 사용하십시오 .

 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);


답변

당신은에보고해야 석영 은 EE 및 SE 버전에서 작동하고 특정 시간을 실행하는 작업을 정의 할 수 있습니다 느릅 나무 자바 프레임 워크의


답변

이 방법으로 시도->

먼저 작업을 실행하는 TimeTask 클래스를 만듭니다.

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

그런 다음 메인 클래스에서 작업을 인스턴스화하고 지정된 날짜까지 주기적으로 시작합니다.

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


답변

AbstractScheduledService아래와 같이 Google Guava 를 사용하십시오 .

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

}

이와 같은 추가 서비스가있는 경우 모든 서비스를 함께 시작하고 중지 할 수 있으므로 ServiceManager에 모든 서비스를 등록하는 것이 좋습니다. 읽기 여기 에서는 ServiceManager에 대한 자세한 내용은.


답변

을 사용하려는 경우 java.util.Timer이를 사용하여 많은 시간 간격으로 예약 할 수 있습니다. 촬영하는 기간 만 지나면됩니다. 여기 에서 설명서를 확인 하십시오 .


답변

이 두 클래스는 정기적 인 작업을 예약하기 위해 함께 작동 할 수 있습니다.

예약 된 작업

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now;
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

예약 된 작업 실행

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

참조 https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/


답변

애플리케이션이 이미 Spring 프레임 워크를 사용중인 경우 스케줄링이 내장되어 있습니다.