国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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)度工廠實(shí)例化后,經(jīng)過(guò)timeout時(shí)間開(kāi)始執(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("定時(shí)任務(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)度工廠實(shí)例化后,經(jīng)過(guò)0秒開(kāi)始執(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運(yùn)行一次 -->  
  <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)度進(jìn)行中...");  
 }  
 }

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>

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

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

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

org.springframework.scheduling.quartz.SimpleTriggerBean

org.springframework.scheduling.quartz.CronTriggerBean

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

配置方式如下:

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

第二種CronTriggerBean,支持到指定時(shí)間運(yùn)行一次,如每天12:00運(yùn)行一次等。

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

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

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

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

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

第五步:?jiǎn)?dòng)你的應(yīng)用即可,即將工程部署至tomcat或其他容器。

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

其實(shí)可以看出Quartz的配置看上去還是挺復(fù)雜的,沒(méi)有辦法,因?yàn)镼uartz其實(shí)是個(gè)重量級(jí)的工具,如果我們只是想簡(jiǎn)單的執(zhí)行幾個(gè)簡(jiǎn)單的定時(shí)任務(wù),有沒(méi)有更簡(jiǎn)單的工具,有!

Spring-Task

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

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

第一種:配置文件方式

第一步:編寫(xiě)作業(yè)類(lèi)

即普通的pojo,如下:

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

第二步:在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 " />

說(shuō)明:ref參數(shù)指定的即任務(wù)類(lèi),method指定的即需要運(yùn)行的方法,cron及cronExpression表達(dá)式,具體寫(xiě)法這里不介紹了,詳情見(jiàn)上篇文章附錄。

這個(gè)配置不消多說(shuō)了,spring掃描注解用的。

到這里配置就完成了,是不是很簡(jiǎn)單。

第二種:使用注解形式

也許我們不想每寫(xiě)一個(gè)任務(wù)類(lèi)還要在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();
}

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

cron:指定cron表達(dá)式

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.即表示從上一個(gè)任務(wù)完成開(kāi)始到下一個(gè)任務(wù)開(kāi)始的間隔,單位是毫秒。

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.即從上一個(gè)任務(wù)開(kāi)始到下一個(gè)任務(wù)開(kāi)始的間隔,單位是毫秒。

下面我來(lái)配置一下。

第一步:編寫(xiě)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ù)進(jìn)行中。。?!?;
    }
}

第二步:添加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" />

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

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

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

更多編程相關(guān)知識(shí),請(qǐng)?jiān)L問(wè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
1502
276
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.

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

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

How does garbage collection work in Java? How does garbage collection work in Java? Aug 02, 2025 pm 01:55 PM

Java's garbage collection (GC) is a mechanism that automatically manages memory, which reduces the risk of memory leakage by reclaiming unreachable objects. 1.GC judges the accessibility of the object from the root object (such as stack variables, active threads, static fields, etc.), and unreachable objects are marked as garbage. 2. Based on the mark-clearing algorithm, mark all reachable objects and clear unmarked objects. 3. Adopt a generational collection strategy: the new generation (Eden, S0, S1) frequently executes MinorGC; the elderly performs less but takes longer to perform MajorGC; Metaspace stores class metadata. 4. JVM provides a variety of GC devices: SerialGC is suitable for small applications; ParallelGC improves throughput; CMS reduces

Comparing Java Build Tools: Maven vs. Gradle Comparing Java Build Tools: Maven vs. Gradle Aug 03, 2025 pm 01:36 PM

Gradleisthebetterchoiceformostnewprojectsduetoitssuperiorflexibility,performance,andmoderntoolingsupport.1.Gradle’sGroovy/KotlinDSLismoreconciseandexpressivethanMaven’sverboseXML.2.GradleoutperformsMaveninbuildspeedwithincrementalcompilation,buildcac

go by example defer statement explained go by example defer statement explained Aug 02, 2025 am 06:26 AM

defer is used to perform specified operations before the function returns, such as cleaning resources; parameters are evaluated immediately when defer, and the functions are executed in the order of last-in-first-out (LIFO); 1. Multiple defers are executed in reverse order of declarations; 2. Commonly used for secure cleaning such as file closing; 3. The named return value can be modified; 4. It will be executed even if panic occurs, suitable for recovery; 5. Avoid abuse of defer in loops to prevent resource leakage; correct use can improve code security and readability.

Using HTML `input` Types for User Data Using HTML `input` Types for User Data Aug 03, 2025 am 11:07 AM

Choosing the right HTMLinput type can improve data accuracy, enhance user experience, and improve usability. 1. Select the corresponding input types according to the data type, such as text, email, tel, number and date, which can automatically checksum and adapt to the keyboard; 2. Use HTML5 to add new types such as url, color, range and search, which can provide a more intuitive interaction method; 3. Use placeholder and required attributes to improve the efficiency and accuracy of form filling, but it should be noted that placeholder cannot replace label.

See all articles