Use Spring-boot to create a timed task. Simultaneous creation of multi-threaded execution of timed tasks.

Source: Internet
Author: User

1, download spring-boot maven project: http://start.spring.io/directly customize the project name.

2, Start class add Note: @EnableScheduling

Specific business code:

Package com.huike.ftp.main;

Import Java.util.Date;
Import Java.util.concurrent.Executor;

Import Org.apache.logging.log4j.LogManager;
Import Org.apache.logging.log4j.Logger;
Import Org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
Import Org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import Org.springframework.scheduling.TaskScheduler;
Import Org.springframework.scheduling.Trigger;
Import Org.springframework.scheduling.TriggerContext;
Import Org.springframework.scheduling.annotation.AsyncConfigurer;
Import org.springframework.scheduling.annotation.EnableScheduling;
Import Org.springframework.scheduling.annotation.SchedulingConfigurer;
Import Org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
Import Org.springframework.scheduling.config.ScheduledTaskRegistrar;
Import Org.springframework.scheduling.support.CronTrigger;
Import org.springframework.stereotype.Component;

Import Com.huike.ftp.model.TransferPo;
Import Com.huike.ftp.service.ParseFile;
Import Com.huike.ftp.service.SftpUtil;

@Configuration
@Component
@EnableScheduling
public class Dynamictransfer implements Schedulingconfigurer, Asyncconfigurer {

Private final Logger Logger = Logmanager.getlogger (GetClass ());

/**
* Parallel Task Usage policy: Multithreading
*
* @return Threadpooltaskscheduler thread pool
*/
@Bean (Destroymethod = "shutdown")
Public Threadpooltaskscheduler TaskScheduler () {
Threadpooltaskscheduler Scheduler = new Threadpooltaskscheduler ();
Scheduler.setpoolsize (3);
Scheduler.setthreadnameprefix ("task-");
Scheduler.setawaitterminationseconds (60);
Scheduler.setwaitfortaskstocompleteonshutdown (TRUE);
return scheduler;
}

/*
* Asynchronous Task
*/
@Override
Public Executor Getasyncexecutor () {
Executor Executor = TaskScheduler ();
return executor;
}

/*
* Asynchronous Task exception handling
*/
@Override
Public Asyncuncaughtexceptionhandler Getasyncuncaughtexceptionhandler () {
return new Simpleasyncuncaughtexceptionhandler ();
}

@Override
public void Configuretasks (Scheduledtaskregistrar taskregistrar) {
TaskScheduler TaskScheduler = TaskScheduler ();
Taskregistrar.settaskscheduler (TaskScheduler);
for (Transferpo transferPo:ParseFile.list) {
Schedule (Taskregistrar, Transferpo);
}

}

private void Schedule (Scheduledtaskregistrar Taskregistrar, Transferpo Transferpo) {
Taskregistrar.addtriggertask (New Runnable () {
@Override
public void Run () {
try {
Logger.info ("Perform file Migration:" + transferpo.tostring ());
New Sftputil (). Programe (Transferpo);
} catch (Exception e) {
Logger.error ("Operation Error", E);
}
}
}, New Trigger () {
@Override
Public Date nextexecutiontime (Triggercontext triggercontext) {
Timed task trigger, can modify the execution period of the scheduled task
Crontrigger trigger = new Crontrigger (Transferpo.getcron ());
Date nextexecdate = Trigger.nextexecutiontime (Triggercontext);
return nextexecdate;
}
});
}
}

Note that in the entire business code, a cron expression is set up, and the business logic in the corresponding thread is executed on a timed basis.

Test Class Code:

Package com.huike.ftp.main;

Import Com.huike.ftp.service.ParseFile;
Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Ftpmain {

/**
* Start the Portal
*
* @param args
* @throws Exception
*/
public static void Main (string[] args) throws Exception {
if (args = = NULL | | Args.length < 1) {
throw new Exception ("Please pass the parameters of the absolute path of the hkftp.properties file");
}
Parsefile.attributes (Args[0]);

Springapplication.run (Ftpmain.class, args);

}
}

Caveats: The test class and the corresponding code need to be placed under the same package.

I created a MAVEN project where I set up the main class for packaging and put all dependent packages into jar packages. Note the packaging method.

So the specific pom file is as follows:

<?xml version= "1.0" encoding= "UTF-8"?>
<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
<modelVersion>4.0.0</modelVersion>

<groupId>com.huike.ftp.hkftp</groupId>
<artifactId>hkftp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>hkftp</name>
<description>demo Project for Spring boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativepath/> <!--lookup parent from repository--
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupid>commons-logging</groupid>
<artifactid>commons-logging </artifactid>
<version>1.1.3</version>
</dependency>
<dependency>
<groupid>org.slf4j</groupid>
<artifactid>slf4j-log4j12</artifactid>
<version >1.7.21</version>
<scope>test</scope>
</dependency>
<!--https:// Mvnrepository.com/artifact/com.jcraft/jsch-->
<dependency>
<groupid>com.jcraft</ Groupid>
<artifactid>jsch</artifactid>
<version>0.1.42</version>
</ Dependency>,
<!--Https://mvnrepository.com/artifact/org.apache.directory.studio/org.apache.commons.io- ->
<dependency>
<groupid>org.apache.directory.studio</groupid>
<artifactId >org.apache.commons.io</artifactid>
<version>2.4</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
<mainClass>com.huike.ftp.main.FtpMain</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<archive>
<manifest>
<mainClass>com.huike.ftp.main.FtpMain</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-jar</id>
<!--binding to the package life cycle phase--
<phase>package</phase>
<goals>
<!--binding to the package life cycle phase--
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

Use Spring-boot to create a timed task. Simultaneous creation of multi-threaded execution of timed tasks.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.