JAVA

[번역] cron4j quickstart

석이 2022. 4. 1. 19:52

Quickstart

cron4j의 주 엔티티는 스케줄러이다. it.sauronsoftware.cron4j.Scheduler 객체를 사용하면 결정된 시간에 코드를 실행할 수 있다. 스케줄러는 매분마다, 매 5분마다 작동될 수도 '금요일 10시', '토요일을 제외한 2월 16일 오후 12시 30분'처럼 구체적인 시간으로 작동될 수도 있다.

 

cron4j 스케줄러의 사용법은 다음 4단계를 따른다.

  1. 스케줄러 객체를 생성한다.
  2. 필요한 스케줄을 작성한다. 스케줄을 작성하기 위해 스케줄러가 무엇을, 언제 할지를 결정한다. 이러한 작업은 java.lang.Runnable 혹은 it.sauronsoftware.cron4j.Task 객체를 사용하여 명시할 수 있고, 문자열 혹은 it.sauronsoftware.cron4j.SchedulingPattern 객체로 나타나는 스케줄링 패턴을 지정할 수 있다.
  3. 스케줄러를 시작한다.
  4. 더이상 필요하지 않을 때, 스케줄러를 종료한다.

아래의 간단한 예를 살펴보자.

import it.sauronsoftware.cron4j.Scheduler;

public class Quickstart {

	public static void main(String[] args) {
		// 스케줄러 객체 생성
		Scheduler s = new Scheduler();
		// 일분마다 실행되는 스케줄
		s.schedule("* * * * *", new Runnable() {
			public void run() {
				System.out.println("Another minute ticked away...");
			}
		});
		// 스케줄러 시작
		s.start();
		// 10분동안 지속된다.
		try {
			Thread.sleep(1000L * 60L * 10L);
		} catch (InterruptedException e) {
			;
		}
		// 스케줄러 종료
		s.stop();
	}

}

위의 예는 10분 동안 동작한다. 매 분이 지날 때마다, 슬프지만 (사실인) "또다른 1분이 지나갔군요..."라는 메세지를 출력한다.

아래는 몇몇 핵심 개념을 나타낸다.

  • 스케줄러는 원하는 수만큼의 모든 스케줄을 처리할 수 있다.
  • 스케줄러는 사용자가 원할 때 설정할 수도, 실행된 이후에 설정할 수도 있다.
  • 스케줄러는 이미 스케줄된 작업의 패턴을 동작하는 동안 바꿀 수 있다. (재설정 작동 - reschedule operation)
  • 이전에 스케줄된 작업을 동작하는 와중에도 제거할 수 있다. (비활성 작동 - deschedule operation)
  • 스케줄러는 원하는 횟수만큼 얼마든지 시작되고 종료될 수 있다.
  •  파일에서 스케줄링할 수 있다. (무슨 말이지..)
  • 원하는 모든 소스로부터 스케줄링할 수 있다.
  • 실행된 작업에 대한 이벤트를 수신하기 위해 스케줄에 대한 리스너를 제공할 수 있다.
  • 진행 중인 모든 작업을 제어할 수 있다.
  • 작업은 스케줄링 패턴 없이 수동으로 작동될 수 있다.
  • 스케줄러의 Time Zone을 바꿀 수 있다.
  • 스케줄러를 사용하기 전, 스케줄링 패턴을 검증(validate)할 수 있다.
  • 스케줄링 패턴에 의한 작업 실행을 예측할 수 있다.

 

Quickstart

The cron4j main entity is the scheduler. With a it.sauronsoftware.cron4j.Scheduler instance you can execute tasks at fixed moments, during all the year. A scheduler can execute a task once a minute, once every five minutes, Friday at 10:00, on February the 16th at 12:30 but only if it is Saturday, and so on.

The use of the cron4j scheduler is a four steps operation:

  1. Create your Scheduler instance.
  2. Schedule your actions. To schedule an action you have to tell the scheduler what it has to do and when. You can specify what using a java.lang.Runnable or a it.sauronsoftware.cron4j.Task instance, and you can specify when using a scheduling pattern, which can be represented with a string or with a it.sauronsoftware.cron4j.SchedulingPattern instance.
  3. Starts the scheduler.
  4. Stops the scheduler, when you don't need it anymore.

Consider this simple example:

import it.sauronsoftware.cron4j.Scheduler;

public class Quickstart {

	public static void main(String[] args) {
		// Creates a Scheduler instance.
		Scheduler s = new Scheduler();
		// Schedule a once-a-minute task.
		s.schedule("* * * * *", new Runnable() {
			public void run() {
				System.out.println("Another minute ticked away...");
			}
		});
		// Starts the scheduler.
		s.start();
		// Will run for ten minutes.
		try {
			Thread.sleep(1000L * 60L * 10L);
		} catch (InterruptedException e) {
			;
		}
		// Stops the scheduler.
		s.stop();
	}

}

This example runs for ten minutes. At every minute change it will print the sad (but true) message "Another minute ticked away...".

Some other key concepts:

  • You can schedule how many tasks you want.
  • You can schedule a task when you want, also after the scheduler has been started.
  • You can change the scheduling pattern of an already scheduled task, also while the scheduler is running (reschedule operation).
  • You can remove a previously scheduled task, also while the scheduler is running (deschedule operation).
  • You can start and stop a scheduler how many times you want.
  • You can schedule from a file.
  • You can schedule from any source you want.
  • You can supply listeners to the scheduler in order to receive events about the executed task.
  • You can control any ongoing task.
  • You can manually launch a task, without using a scheduling pattern.
  • You can change the scheduler working Time Zone.
  • You can validate your scheduling patterns before using them with the scheduler.
  • You can predict when a scheduling pattern will cause a task execution.