之前做了一个上传压缩文件到ftp服务的功能,为了防止有些文件没有按正常流程被删除,做一个定时任务每天定时扫描ftp服务器并删除压缩文件,防止积压。
引入依赖
<dependency>
<groupId>com.zenpower</groupId>
<artifactId>zenos-quartz-spring-boot-starter</artifactId>
</dependency>
在yml文件配置连接信息
由于服务配置文件在nacos上,我不便展示。可自行搜索一下如何配置。
在项目启动类加注解
//你的定时任务所在的包名
@QuartzTaskScan(basePackages = "com.company.test.quart")
编写定时任务代码
注意:获取ftp连接方法不是通用的,你们需要修改成自己的,以下只是案例。
/**
* 定时删除ftp服务的zip文件、redis中存储的zip文件信息
* 每天凌晨1点执行
*
*/
@Slf4j
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@CronSchedule(cron = "0 0 1 * * ?")
//@CronSchedule(cron = "0/10 * * * * ?")
@QuartzTask(
trigger = @QuartzTrigger(key = @Key(name = "DeleteZipQuartzTaskTrigger")),
jobDetail = @QuartzJobDetail(key = @Key(name = "DeleteZipQuartzTaskJob"), jobClass = DeleteZipQuartz.class)
)
public class DeleteZipQuartz extends TenantQuartzJob {
@Autowired
private FtpInfoFeignApi ftpInfoFeignApi;
@Autowired
private RedisTemplate redisTemplate;
@Override
protected void executeTenantInternal(JobExecutionContext content) throws JobExecutionException {
String tenant = TenantThreadLocal.getTenant();
if (tenant == null) {
throw new BusinessException("定时任务无法获取租户信息");
}
FtpInfoDto ftpInfo = ftpInfoFeignApi.getFtpInfoDto();
if (ftpInfo == null) {
throw new BusinessException("定时任务无法获取ftp连接信息");
} else {
String filePath = ftpInfo.getBasePath() + "/存储路径/";
try (Ftp ftp = new Ftp(ftpInfo.getAddress(), Integer.parseInt(ftpInfo.getPort()), ftpInfo.getUsername(), ftpInfo.getPassword(), Charsets.UTF_8)) {
ftp.setMode(FtpMode.Passive);
// 获取指定路径下的所有文件名
List<String> fileNames = ftp.ls(filePath);
for (String fileName : fileNames) {
// 如果是zip文件,则删除
if (fileName.endsWith(".zip")) {
ftp.delFile(filePath + fileName);
String key = "zipFileID:"+fileName.substring(0, 36);
redisTemplate.delete(key);
}
}
} catch (Exception e) {
log.error("定时任务删除ftp压缩文件失败: {}", e.getMessage(), e);
}
}
}
}