programing

Java에서 정기적인 작업을 스케줄링하려면 어떻게 해야 합니까?

goodcopy 2022. 8. 3. 21:37
반응형

Java에서 정기적인 작업을 스케줄링하려면 어떻게 해야 합니까?

일정 시간 간격으로 실행할 작업을 예약해야 합니다.긴 간격(8시간마다 등)을 지원하려면 어떻게 해야 합니까?

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

Scheduled Executor Service 사용:

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

Quartz는 EE 및 SE 에디션과 연계하여 작업을 정의하고 특정 시간을 실행할 수 있는 Java 프레임워크입니다.

이렇게 해보세요->

먼저 작업을 실행하는 클래스의 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));
}

Google Guava 사용AbstractScheduledService다음과 같이 합니다.

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

이와 같은 서비스가 더 많으면 모든 서비스를 동시에 시작하고 중지할 수 있으므로 Service Manager에 모든 서비스를 등록하는 것이 좋습니다.Service Manager에 대한 자세한 내용은 여기를 참조하십시오.

계속 하고 싶다면java.util.Timer를 사용하면, 큰 시간 간격으로 스케줄을 설정할 수 있습니다.당신은 그저 당신이 찍고 있는 기간을 지나칠 뿐이다. 문서를 참조하십시오.

매초 뭔가를 하다

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //code
    }
}, 0, 1000);

다음 2개의 클래스가 연동하여 정기적인 작업을 스케줄링할 수 있습니다.

스케줄링된 작업

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 프레임워크를 사용하고 있는 경우 Scheduling이 내장되어 있습니다.

Spring Framework의 기능을 사용하고 있습니다.(스프링-스프링 병 또는 메이브 의존성).

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Component
public class ScheduledTaskRunner {

    @Autowired
    @Qualifier("TempFilesCleanerExecution")
    private ScheduledTask tempDataCleanerExecution;

    @Scheduled(fixedDelay = TempFilesCleanerExecution.INTERVAL_TO_RUN_TMP_CLEAN_MS /* 1000 */)
    public void performCleanTempData() {
        tempDataCleanerExecution.execute();
    }

}

Scheduled Task는 커스텀 메서드 실행이 포함된 나만의 인터페이스입니다.이것을 스케줄된 태스크라고 부릅니다.

주석을 사용하여 스프링 스케줄러를 사용해 본 적이 있습니까?

@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
    //body can be another method call which returns some value.
}

xml에서도 이 작업을 수행할 수 있습니다.

 <task:scheduled-tasks>
   <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
 <task:scheduled-tasks>

my servlet에는 사용자가 accept를 눌렀을 때 스케줄러에 이를 유지하는 코드로 포함되어 있습니다.

if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}

이 있습니다.ScheduledFuturejava.discurrent.concurrent의 클래스가 도움이 될 수 있습니다.

언급URL : https://stackoverflow.com/questions/7814089/how-to-schedule-a-periodic-task-in-java

반응형