1. 程式人生 > >使用spring-boot創建定時任務。同時創建多線程執行定時任務。

使用spring-boot創建定時任務。同時創建多線程執行定時任務。

from vnr thread make oca 工程 遷移 prefix gist

1,下載spring-boot的maven工程:http://start.spring.io/ 直接自定義工程名稱。

2 , 啟動類增加註解:@EnableScheduling

具體的業務代碼:

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());

/**
* 並行任務使用策略:多線程處理
*
* @return ThreadPoolTaskScheduler 線程池
*/
@Bean(destroyMethod = "shutdown")
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(3);
scheduler.setThreadNamePrefix("task-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
}

/*
* 異步任務
*/
@Override
public Executor getAsyncExecutor() {
Executor executor = taskScheduler();
return executor;
}

/*
* 異步任務 異常處理
*/
@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("執行文件遷移:" + transferPo.toString());
new SftpUtil().programe(transferPo);
} catch (Exception e) {
logger.error("運行報錯", e);
}
}
}, new Trigger() {
@Override
public Date nextExecutionTime(TriggerContext triggerContext) {
// 定時任務觸發,可修改定時任務的執行周期
CronTrigger trigger = new CronTrigger(transferPo.getCron());
Date nextExecDate = trigger.nextExecutionTime(triggerContext);
return nextExecDate;
}
});
}
}

註意在整個的業務代碼當中,設置了應對的cron表達式,定時的執行相應線程中的業務邏輯。

測試類代碼:

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 {

/**
* 啟動入口
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args == null || args.length < 1) {
throw new Exception("請傳入hkftp.properties文件絕對路徑的參數");
}
ParseFile.attributes(args[0]);

SpringApplication.run(FtpMain.class, args);

}
}

註意事項:測試類和相對應的代碼需要放在同一個包下面。

我創建的maven工程項目,其中設置打包的主類和將所有依賴的包都打成jar包。註意打包方式。

所以具體的pom文件如下:

<?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>
<!-- 綁定到package生命周期階段上 -->
<phase>package</phase>
<goals>
<!-- 綁定到package生命周期階段上 -->
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

使用spring-boot創建定時任務。同時創建多線程執行定時任務。