search
HomeJavajavaTutorialSeveral methods to implement timing scheduling in Spring

This article mainly introduces examples of timing scheduling in Spring. The system can perform certain functions at a certain time when no one is on duty. Those who are interested can learn more.

1, Content Introduction

The so-called scheduled scheduling refers to a mechanism by which the system can perform certain specific functions at a certain time when no one is on duty. For traditional In terms of development, scheduled scheduling operations are divided into two forms:

Scheduled triggering: perform certain processing operations at a certain point in time;

Interval triggering: performed every few seconds Automatic processing of certain operations.

All processing relies on the underlying clock generator of the computer system. In the initial implementation process of Java, there are two classes specifically provided for timing processing: Timer and TimerTask, of which TimerTask is mainly Defining the execution of tasks is equivalent to starting a thread to perform certain tasks.

public class MyTask extends TimerTask{

  @Override

  public void run() {//定义要执行的任务

    // TODO Auto-generated method stub

    String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());

    System.out.println(currentTime);

  } 

}

public class MyTaskTest {

  public static void main(String[] args) {

    Timer timer=new Timer();

    timer.schedule(new MyTask(), 1000);//启动任务,延迟1秒后执行。

  } 

}

However, if you are required to perform a task at a certain time, minute and second in a certain month every year, there is nothing you can do using Timer and TimerTask. In project development, there are often two choices for timing control:

quartz component: enterprise and timing scheduling components, which need to be configured separately;

SpringTask: lightweight component, simple configuration, can Use Annotation to implement configuration processing.

2, Quartz defines timing scheduling

To use the Quartz component, we need to import the quartz development package and add the quartz development package in pom.xml.

<dependency>

      <groupid>org.quartz-scheduler</groupid>

      <artifactid>quartz</artifactid>

      <version>2.2.3</version>

</dependency>

After introducing the package, you can develop scheduled scheduling.

There are two implementation modes:

To inherit the QuartzJobBean parent class;

You can directly use the configuration to realize the scheduling control of the method.

1, inherit a parent class to implement task processing.

public class MyTask2 extends QuartzJobBean{

  @Override

  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

    // TODO Auto-generated method stub

        String currentTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());

        System.out.println(currentTime);

        System.out.println("具体的任务实现!!!");

  }

}

All scheduled scheduling must be enabled in the Spring control file, that is, there is no need to write an explicit class to enable scheduled tasks. .

2. Add the scheduled scheduling configuration in the applicationContext.xml file and implement it through the scheduled scheduling factory class.

<bean>

    <property></property>

    <property>

      <map>

        <entry></entry>

      </map>

    </property>

  </bean>

Then configure the trigger job of the task. There are two types of job configurations:

Use interval trigger: repeat execution after a certain period of time;

Factory class: org.springframework.scheduling.quartz.SimpleTriggerFactoryBean

<bean>

    <!-- 定义间隔触发的执行程序类 -->

    <property></property>

    <!-- 设置定时触发延迟时间 -->

    <property></property>

    <!-- 单位是”毫秒“ -->

    <property></property>

  </bean>

Set interval trigger scheduler: org.springframework.scheduling.quartz .SchedulerFactoryBean

<bean>

    <property>

      <list>

        <ref></ref>

      </list>

    </property>

  </bean>

3. At this time, all interval triggering controls are managed by Spring. Now you only need to start the Spring container to implement interval triggering tasks.

Use Cron to achieve scheduled triggering

Quartz can not only achieve interval triggering, it can also be combined with Cron to achieve scheduled triggering, which is also its most important function.

The most commonly used modes in general projects: trigger on the hour, trigger at the beginning of the month, and trigger at the beginning of the year.

Modify the previous interval trigger configuration and use CronTriggerFactoryBean to implement scheduled triggering.

<bean>

    <property></property>

    <property>

      <map>

        <entry></entry>

      </map>

    </property>

  </bean>

  <bean>

    <property></property>

    <!-- cron表达式,描述每分钟触发一次 -->

    <property></property>

  </bean>

  <bean>

    <property>

      <list>

        <ref></ref>

      </list>

    </property>

  </bean>

Just start the Spring container.

2, do not inherit any class to implement timing scheduling

In project development, inheritance will directly lead to the limited control of single inheritance, so in this case, Spring provides a way to avoid Inheriting any class can implement task processing for scheduled operations.

Define a task execution class and do not inherit any class.

public class MyTask2 {

  public void taskSelf(){

    String task=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new java.util.Date());

    System.out.println(task);

    System.out.println("执行具体任务操作");

  }

}

Configure the factory class in applicationContext.xml: org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean

<bean>

    <property>

      <bean></bean>

    </property>

    <!--配置要执行的方法 -->

    <property></property>

  </bean>

Then configure a new program class in the task scheduling configuration

<bean>

    <property></property>

    <!-- cron表达式,描述每分钟触发一次 -->

    <property></property>

  </bean>

Start the container to achieve scheduled scheduling.

This mode has no inheritance dependencies of classes, and the processing will be more flexible.

Spring Task implements scheduled scheduling

Spring has its own support for scheduled scheduling, and it feels even easier to use than Quartz.

It has two implementation methods, 1. Configure the implementation in applicationContext.xml; 2. Use Annotation to implement it.

But which mode to use, you must first have a task processing class.

Define task processing class.

The previous MyTask2 class is used directly here and will not be written again.

Modify the applicationContext.xml file:

Need to add a namespace definition for task processing:

 <beans http:></beans>

1 Configure task operation Configuration to achieve interval triggering.

<bean></bean>

  <scheduled-tasks>

    <scheduled></scheduled>

  </scheduled-tasks>

Use cron to implement scheduled triggering

<bean></bean>

  <scheduled-tasks>

    <scheduled></scheduled>

  </scheduled-tasks>

It can be seen that SpringTask is simpler to implement .

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more related articles on several methods of implementing timing scheduling in Spring, please pay attention to the PHP Chinese website!

Statement
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
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.