정기적으로 실행되도록 작업을 예약하려면 어떻게합니까?
예약 된 작업을 구현하기 위해 몇 가지 코드를 시도하고 이러한 코드를 생각해 냈습니다.
import java.util.*;
class Task extends TimerTask {
int count = 1;
// run is a abstract method that defines task performed at scheduled time.
public void run() {
System.out.println(count+" : Mahendra Singh");
count++;
}
}
class TaskScheduling {
public static void main(String[] args) {
Timer timer = new Timer();
// Schedule to run after every 3 second(3000 millisecond)
timer.schedule( new Task(), 3000);
}
}
내 출력 :
1 : Mahendra Singh
컴파일러가 3 초 간격으로 일련의 Mahendra Singh을 인쇄 할 것으로 예상했지만 약 15 분 동안 기다렸음에도 불구하고 하나의 출력 만 표시됩니다. 어떻게 해결합니까?
사용하다 timer.scheduleAtFixedRate
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
지정된 지연 후에 시작하여 반복되는 고정 속도 실행을 위해 지정된 작업을 예약합니다. 후속 실행은 지정된 기간으로 구분 된 대략 일정한 간격으로 발생합니다.
고정 속도 실행에서 각 실행은 초기 실행의 예약 된 실행 시간을 기준으로 예약됩니다. 어떤 이유로 든 실행이 지연되는 경우 (예 : 가비지 수집 또는 기타 백그라운드 활동) "추격"을 위해 두 번 이상의 실행이 연속적으로 발생합니다. 장기적으로 실행 빈도는 정확히 지정된 기간의 역수입니다 (Object.wait (long)의 기본 시스템 시계가 정확하다고 가정).
고정 속도 실행은 매시간 차임벨을 울리거나 특정 시간에 매일 예약 된 유지 관리를 실행하는 것과 같이 절대 시간에 민감한 반복 활동에 적합합니다. 또한 10 초 동안 1 초에 한 번씩 틱하는 카운트 다운 타이머와 같이 고정 된 수의 실행을 수행하는 총 시간이 중요한 반복 활동에도 적합합니다. 마지막으로 고정 속도 실행은 서로 동기화 상태를 유지해야하는 여러 반복 타이머 작업을 예약하는 데 적합합니다.
매개 변수 :
- task-예약 할 작업.
- 지연-작업이 실행되기 전 지연 시간 (밀리 초).
- period-연속 작업 실행 사이의 시간 (밀리 초)입니다.
던졌습니다 :
- IllegalArgumentException-delay가 음수이거나 delay + System.currentTimeMillis ()가 음수 인 경우
- IllegalStateException-작업이 이미 예약 또는 취소 된 경우 타이머가 취소되었거나 타이머 스레드가 종료되었습니다.
ScheduledExecutorService
오버의 장점Timer
ScheduledExecutorService 인터페이스 의 구현 인 -ScheduledThreadPoolExecutorTimer
사용에 대한 대안을 제공하고 싶습니다 . "Java in Concurrency"에 따르면 Timer 클래스에 비해 몇 가지 장점이 있습니다.
A
Timer
는 타이머 작업을 실행하기위한 단일 스레드 만 만듭니다. 타이머 작업을 실행하는 데 너무 오래 걸리면 다른 사람의 타이밍 정확도가TimerTask
떨어질 수 있습니다. 반복TimerTask
작업이 10ms마다 실행되도록 예약되고 다른 Timer-Task를 실행하는 데 40ms가 소요되는 경우 반복 작업 (고정 속도로 예약되었는지 고정 지연으로 예약되었는지에 따라 다름)은 긴 시간 후에 빠르게 연속해서 4 번 호출됩니다. 실행중인 작업이 완료되거나 4 개의 호출이 완전히 "누락"됩니다. 예약 된 스레드 풀은 지연 및 주기적 작업을 실행하기 위해 여러 스레드를 제공 할 수 있도록하여 이러한 제한을 해결합니다.
Timer의 또 다른 문제 TimerTask
는 검사되지 않은 예외가 발생 하면 제대로 작동하지 않는다는 것 입니다. "스레드 누출"이라고도합니다.
The Timer thread doesn't catch the exception, so an unchecked exception thrown from a
TimerTask
terminates the timer thread. Timer also doesn't resurrect the thread in this situation; instead, it erroneously assumes the entire Timer was cancelled. In this case, TimerTasks that are already scheduled but not yet executed are never run, and new tasks cannot be scheduled.
고유 한 일정 관리 서비스를 구축해야하는 경우 또 다른 권장 사항 은의 일정 예약 기능을 제공 DelayQueue
하는 BlockingQueue
구현 인을 사용하여 라이브러리를 계속 활용할 수 있습니다 ScheduledThreadPoolExecutor
. A DelayQueue
는 지연된 개체의 컬렉션을 관리합니다. Delayed에는 관련 지연 시간 DelayQueue
이 있습니다. 지연이 만료 된 경우에만 요소를 가져올 수 있습니다. 개체는 DelayQueue
지연과 관련된 시간에 따라 정렬됩니다.
public void schedule(TimerTask task,long delay)
지정된 지연 후 실행할 지정된 작업을 예약합니다.
당신이 원하는 :
public void schedule(TimerTask task, long delay, long period)
지정된 지연 후에 시작 하여 반복 된 고정 지연 실행을 위해 지정된 작업을 예약합니다 . 후속 실행은 지정된 기간으로 구분 된 대략 정기적 인 간격으로 발생합니다.
Quartz scheduler is also a solution and firstly you make Quartz Job class.
Quartz job is defined what you want to run
package com.blogspot.geekonjava.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
public class QuartzJob implements Job {
public void execute(JobExecutionContext context)
throws JobExecutionException {
JobKey jobKey = context.getJobDetail().getKey();
System.out.println("Quartz" + "Job Key " + jobKey);
}
}
Now you need to make Quartz Trigger
There are two types of triggers in Quartz
SimpleTrigger – Allows to set start time, end time, repeat interval.
Trigger trigger = newTrigger().withIdentity("TriggerName", "Group1")
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(10).repeatForever()).build();
CronTrigger – Allows Unix cron expression to specify the dates and times to run your job.
Trigger trigger = newTrigger()
.withIdentity("TriggerName", "Group2")
.withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")).build();
Scheduler class links both Job and Trigger together and execute it.
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
timer.scheduleAtFixedRate( new Task(), 1000,3000);
For this purpose Java has Timer and TimerTask class but what is it ?
- java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
- java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.
You can check full tutorial from GeekonJava
TimerTask timerTask = new MyTimerTask();
//running timer task as daemon thread
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 10*1000);
참고URL : https://stackoverflow.com/questions/4544197/how-do-i-schedule-a-task-to-run-at-periodic-intervals
'Program Tip' 카테고리의 다른 글
jquery 이벤트 핸들러를 덮어 쓰는 방법 (0) | 2020.10.23 |
---|---|
두 필드의 고유성을 확인하는 방법 (0) | 2020.10.23 |
주어진 인덱스에 존재하는 경우 ArrayList 대체 요소? (0) | 2020.10.23 |
새로운 Asp.Net MVC5 프로젝트는 로그인 페이지에 무한 루프를 생성합니다. (0) | 2020.10.23 |
redis로 지속성을 비활성화하는 방법은 무엇입니까? (0) | 2020.10.23 |