>  기사  >  Java  >  Spring은 TimerTask를 통합하여 예약된 작업 스케줄링을 구현합니다.

Spring은 TimerTask를 통합하여 예약된 작업 스케줄링을 구현합니다.

高洛峰
高洛峰원래의
2017-02-07 15:27:351588검색

1. 서문

최근 회사의 프로젝트에서는 TimerTask가 사용되었습니다. 실제로 TimerTask는 실제 프로젝트에서 많이 사용되지 않습니다. 🎜>지정된 시간에 실행할 수 없기 때문에 특정 빈도로만 프로그램을 실행하게 할 수 있습니다.

2. TimerTask


JDK의 Timer는 타이머 클래스입니다. 지정된 예약된 작업을 구성할 수 있습니다.

JDK의 TimerTask는 예약된 작업 클래스입니다. 이 클래스는 Runnable 인터페이스를 구현하며 이 클래스를 상속하여 예약된 작업을 구현할 수 있습니다.

/** 
 * 继承TimerTask实现定时任务 
 */
public class MyTask extends TimerTask { 
  
  @Override
  public void run() { 
    String currentTime = new SimpleDateFormat("yyy-MM-dd hh:mm:ss").format(new Date()); 
    System.out.println(currentTime + " 定时任务正在执行..."); 
  } 
  
  public static void main(String[] args) { 
    Timer timer = new Timer(); 
      
    // 1秒钟执行一次的任务, 参数为: task, delay, peroid 
    timer.schedule(new MyTask(), 2000, 1000); 
  } 
}

세 가지. Spring


의 두 가지 핵심 클래스 통합: ScheduledTimerTask, TimerFactoryBean

ScheduledTimerTask 클래스는 TimerTask의 래퍼 구현으로, 이를 통해 이 작업에 대한 트리거 정보를 정의할 수 있습니다.
TimerFactoryBean 클래스 Spring은 구성을 사용하여 지정된 ScheduledTimerTask 빈 세트에 대한 Timer 인스턴스를 자동으로 생성합니다.

1. Jar 패키지 소개: spring.jar, commons-logging.jar

2.

/** 
 * 定时调度业务类 
 */
public class TaskService extends TimerTask { 
  private int count = 1; 
  
  public void run() { 
    System.out.println("第" + count + "次执行定时任务"); 
    count++; 
  } 
}

3. 핵심 구성:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://www.springframework.org/schema/beans  
  http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 
    
  <bean id="taskService" class="com.zdp.service.TaskService"></bean> 
  <bean id="scheduledTimerTask" class="org.springframework.scheduling.timer.ScheduledTimerTask"> 
    <property name="timerTask" ref="taskService" /> 
      
    <!-- 每隔一天执行一次配置: 24*60*60*1000 -->
    <!-- 每1秒钟程序执行一次 -->
    <property name="period" value="1000" /> 
      
    <!-- 程序启动4秒钟后开始执行 -->
    <property name="delay" value="4000" /> 
  </bean> 
    
  <bean id="timerFactoryBean" class="org.springframework.scheduling.timer.TimerFactoryBean"> 
    <property name="scheduledTimerTasks"> 
      <list> 
        <ref bean="scheduledTimerTask" /> 
      </list> 
    </property> 
  </bean> 
</beans>

4. 테스트 클래스:

public class Main { 
  public static void main(String[] args) { 
    // 加载spring配置文件 
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
    System.out.println("<<-------- 启动定时任务 -------- >>"); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 
    while (true) { 
      try { 
        if (reader.readLine().equals("quit")) { 
          System.out.println("<<-------- 退出定时任务 -------- >>"); 
          System.exit(0); 
        } 
      } catch (IOException e) { 
        throw new RuntimeException("error happens...", e); 
      } 
    } 
  } 
}

위 내용은 모두의 학습에 도움이 되기를 바랍니다. 나는 또한 모든 사람들이 PHP 중국어 웹사이트를 지지해주기를 바랍니다.

예약된 작업 스케줄링을 구현하기 위해 TimerTask를 통합하는 Spring과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.