亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
one. Classification
From the perspective of implementation technology, there are currently three main technologies (or three products):
In terms of inheritance methods of job classes, they can be divided into two categories:
From the trigger timing of task scheduling, here are mainly the triggers used for jobs. There are two main types:
two. Usage instructions
Quartz
First, the job class inherits from a specific base class: org.springframework.scheduling.quartz.QuartzJobBean.
Second, the job class does not inherit a specific base class. (Recommended) " >Second, the job class does not inherit a specific base class. (Recommended)
Spring-Task
第一種:配置文件方式
第二種:使用注解形式
Home Java JavaBase What are the several ways to implement scheduled tasks in Java?

What are the several ways to implement scheduled tasks in Java?

May 25, 2021 pm 02:18 PM
java scheduled tasks

How to implement scheduled tasks in Java: 1. Use the "java.util.Timer" class that comes with Java. This class allows you to schedule a "java.util.TimerTask" task; 2. Use Quartz; 3. , Use the tasks that come with Spring 3.0.

What are the several ways to implement scheduled tasks in Java?

The operating environment of this tutorial: windows7 system, java8 version, DELL G3 computer.

Recently, some scheduled tasks need to be performed during project development. For example, it is necessary to analyze the log information of the previous day in the early morning of every day. I took this opportunity to sort out several implementation methods of scheduled tasks. Since the project uses the spring framework , so I will introduce it in conjunction with the spring framework.

one. Classification

  • From the perspective of implementation technology, there are currently three main technologies (or three products):

    1. Java’s own java.util.Timer Class, this class allows you to schedule a java.util.TimerTask task. Using this method allows your program to be executed at a certain frequency, but not at a specified time. Generally used less, this article will not introduce it in detail.

    2. Use Quartz, which is a relatively powerful scheduler that allows your program to be executed at a specified time or at a certain frequency. The configuration is a bit complicated, and will be discussed later. Detailed introduction.

    3. The tasks that come with Spring 3.0 and later can be regarded as a lightweight Quartz, and it is much simpler to use than Quartz, which will be introduced later.

  • In terms of inheritance methods of job classes, they can be divided into two categories:

    1. Job classes need to inherit from a specific job class base class, such as in Quartz It needs to be inherited from org.springframework.scheduling.quartz.QuartzJobBean; java.util.Timer needs to be inherited from java.util.TimerTask.

    2. The job class is an ordinary java class and does not need to inherit from any base class.

Note: I personally recommend using the second method, because all classes are common classes and do not need to be treated differently in advance.

  • From the trigger timing of task scheduling, here are mainly the triggers used for jobs. There are two main types:

    1. Every specified time. Triggered once, the corresponding trigger in Quartz is: org.springframework.scheduling.quartz.SimpleTriggerBean

    2. Triggered once every specified time, the corresponding scheduler in Quartz is: org.springframework. scheduling.quartz.CronTriggerBean

Note: Not every task can use these two triggers. For example, the java.util.TimerTask task can only use the first one. Both Quartz and spring task can support these two trigger conditions.

two. Usage instructions

Introduces in detail how to use each task scheduling tool, including Quartz and spring task.

Quartz

First, the job class inherits from a specific base class: org.springframework.scheduling.quartz.QuartzJobBean.

The first step: Define the job class

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class Job1 extends QuartzJobBean {

private int timeout;
private static int i = 0;
//調(diào)度工廠實例化后,經(jīng)過timeout時間開始執(zhí)行調(diào)度
public void setTimeout(int timeout) {
this.timeout = timeout;
}

/**
* 要調(diào)度的具體任務(wù)
*/
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
  System.out.println("定時任務(wù)執(zhí)行中…");
}
}

The second step: Configure the job class JobDetailBean in the spring configuration file

<bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.gy.Job1" />
<property name="jobDataAsMap">
<map>
<entry key="timeout" value="0" />
</map>
</property>
</bean>

Description: org.springframework.scheduling.quartz.JobDetailBean has two attributes. The jobClass attribute is the task class we define in the java code, and the jobDataAsMap attribute is the attribute value that needs to be injected into the task class.

Step 3: Configure the triggering method (trigger) of job scheduling

There are two types of job triggers in Quartz, namely

org .springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

The first SimpleTriggerBean only supports calling tasks at a certain frequency, such as running once every 30 minutes .

The configuration method is as follows:

<bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
<property name="jobDetail" ref="job1" />  
<property name="startDelay" value="0" /><!-- 調(diào)度工廠實例化后,經(jīng)過0秒開始執(zhí)行調(diào)度 -->  
<property name="repeatInterval" value="2000" /><!-- 每2秒調(diào)度一次 -->  
</bean>

The second CronTriggerBean supports running once at a specified time, such as once every day at 12:00.

<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
  <property name="jobDetail" ref="job1" />  
  <!—每天12:00運行一次 -->  
  <property name="cronExpression" value="0 0 12 * * ?" />  
  </bean>

See the appendix for the syntax of cronExpression expressions.

Step 4: Configure the scheduling factory

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">  
 <property name="triggers">  
 <list>  
 <ref bean="cronTrigger" />  
 </list>  
 </property>  
</bean>

Description: This parameter specifies the name of the previously configured trigger.

Step 5: Just start your application, that is, deploy the project to tomcat or other containers.

Spring can support this method thanks to two classes:

org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean

org.springframework. scheduling.quartz.MethodInvokingJobDetailFactoryBean

These two classes respectively correspond to the two methods of task scheduling supported by spring, namely the timer task method and the Quartz method that come with java as mentioned above. Here I only write about the usage of MethodInvokingJobDetailFactoryBean. The advantage of using this class is that our task class no longer needs to inherit from any class, but is an ordinary pojo.

Step 1: Write the task class

 public class Job2 {  
 public void doJob2() {  
 System.out.println("不繼承QuartzJobBean方式-調(diào)度進行中...");  
 }  
 }

As you can see, this is an ordinary class and has a method.

Step 2: Configure job class

<bean id="job2"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<bean class="com.gy.Job2" />
</property>
<property name="targetMethod" value="doJob2" />
<property name="concurrent" value="false" /><!-- 作業(yè)不并發(fā)調(diào)度 -->
</bean>

說明:這一步是關(guān)鍵步驟,聲明一個MethodInvokingJobDetailFactoryBean,有兩個關(guān)鍵屬性:targetObject指定任務(wù)類,targetMethod指定運行的方法。往下的步驟就與方法一相同了,為了完整,同樣貼出。

第三步:配置作業(yè)調(diào)度的觸發(fā)方式(觸發(fā)器)

Quartz的作業(yè)觸發(fā)器有兩種,分別是

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

第一種SimpleTriggerBean,只支持按照一定頻度調(diào)用任務(wù),如每隔30分鐘運行一次。

配置方式如下:

 <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">  
 <property name="jobDetail" ref="job2" />  
 <property name="startDelay" value="0" /><!-- 調(diào)度工廠實例化后,經(jīng)過0秒開始執(zhí)行調(diào)度 -->  
 <property name="repeatInterval" value="2000" /><!-- 每2秒調(diào)度一次 -->  
 </bean>

第二種CronTriggerBean,支持到指定時間運行一次,如每天12:00運行一次等。

 <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">  
 <property name="jobDetail" ref="job2" />  
  <!—每天12:00運行一次 -->  
  <property name="cronExpression" value="0 0 12 * * ?" />  
 </bean>

以上兩種方式根據(jù)實際情況任選一種即可

第四步:配置調(diào)度工廠

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>

說明:該參數(shù)指定的就是之前配置的觸發(fā)器的名字。

第五步:啟動你的應(yīng)用即可,即將工程部署至tomcat或其他容器。

到此,spring中Quartz的基本配置就介紹完了,當(dāng)然了,使用之前,要導(dǎo)入相應(yīng)的spring的包與Quartz的包,這些就不消多說了。

其實可以看出Quartz的配置看上去還是挺復(fù)雜的,沒有辦法,因為Quartz其實是個重量級的工具,如果我們只是想簡單的執(zhí)行幾個簡單的定時任務(wù),有沒有更簡單的工具,有!

Spring-Task

上節(jié)介紹了在Spring 中使用Quartz,本文介紹Spring3.0以后自主開發(fā)的定時任務(wù)工具,spring task,可以將它比作一個輕量級的Quartz,而且使用起來很簡單,除spring相關(guān)的包外不需要額外的包,而且支持注解和配置文件兩種

形式,下面將分別介紹這兩種方式。

第一種:配置文件方式

第一步:編寫作業(yè)類

即普通的pojo,如下:

  import org.springframework.stereotype.Service;  
  @Service  
  public class TaskJob {  
        5      public void job1() {  
          System.out.println(“任務(wù)進行中。。?!?;  
      }  
  }

第二步:在spring配置文件頭中添加命名空間及描述

 <beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:task="http://www.springframework.org/schema/task"   
    xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

第三步:spring配置文件中設(shè)置具體的任務(wù)

<task:scheduled-tasks>   
         <task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/>   
</task:scheduled-tasks>  
   
<context:component-scan base-package=" com.gy.mytask " />

說明:ref參數(shù)指定的即任務(wù)類,method指定的即需要運行的方法,cron及cronExpression表達式,具體寫法這里不介紹了,詳情見上篇文章附錄。

這個配置不消多說了,spring掃描注解用的。

到這里配置就完成了,是不是很簡單。

第二種:使用注解形式

也許我們不想每寫一個任務(wù)類還要在xml文件中配置下,我們可以使用注解@Scheduled,我們看看源文件中該注解的定義:

@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled
{
  public abstract String cron();

  public abstract long fixedDelay();

  public abstract long fixedRate();
}

可以看出該注解有三個方法或者叫參數(shù),分別表示的意思是:

cron:指定cron表達式

fixedDelay:官方文檔解釋:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示從上一個任務(wù)完成開始到下一個任務(wù)開始的間隔,單位是毫秒。

fixedRate:官方文檔解釋:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即從上一個任務(wù)開始到下一個任務(wù)開始的間隔,單位是毫秒。

下面我來配置一下。

第一步:編寫pojo

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component(“taskJob”)
public class TaskJob {
    @Scheduled(cron = "0 0 3 * * ?")
    public void job1() {
        System.out.println(“任務(wù)進行中。。?!?;
    }
}

第二步:添加task相關(guān)的配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"
    default-lazy-init="false">


    <context:annotation-config />
    <!—spring掃描注解的配置   -->
    <context:component-scan base-package="com.gy.mytask" />

    <!—開啟這個配置,spring才能識別@Scheduled注解   -->
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
    <task:scheduler id="qbScheduler" pool-size="10"/>

說明:理論上只需要加上這句配置就可以了,這些參數(shù)都不是必須的。

?Ok配置完畢,當(dāng)然spring task還有很多參數(shù),我就不一一解釋了,具體參考xsd文檔http://www.springframework.org/schema/task/spring-task-3.0.xsd。

更多編程相關(guān)知識,請訪問:編程視頻??!

The above is the detailed content of What are the several ways to implement scheduled tasks in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

See all articles