简体   繁体   English

如何在 spring 引导中使用 cron 作业根据指定条件安排作业

[英]How to schedule the job based on specified condition using cron job in spring boot

existing code that run for one bank,my new requirement is based on bank i have to run the schedule job ex: if(bank==city) schedule the job for city bank specific task if(bank==hdfc) schedule the job for hdfc specific task ---- like that please any one can guide me how i can achieve this.Note: bank name is getting based on customer id.为一家银行运行的现有代码,我的新要求基于银行我必须运行计划作业例如: if(bank==city) 为城市银行特定任务安排作业 if(bank==hdfc) 安排作业hdfc 特定任务 ---- 这样请任何人都可以指导我如何实现这一点。注意:银行名称是根据客户 ID 获取的。

 @SpringBootApplication
    @EnableScheduling 
    public class Application implements CommandLineRunner { 
        public static void main(String args[]) {  
            try{
          SpringApplication.run(Application.class); 
            }catch(Exception e){            
            }
        }
        @Override
        public void run(String... args) throws Exception {   
        }   
    }

    service:
    @Component
    public class HolcimSFTPPoolScheduler {

        private SchedulerDetails schedulerDetails = null;
        HolcimSFTPPool holcimSFTPPool = new HolcimSFTPPool();
        PaymentUploadEncription paymentUploadEncription = null;
        PaymentDAO paymentDAO = new PaymentDAO();
        DecryptFile decryptFile = null;
        public HolcimSFTPPoolScheduler() {
            decryptFile = new DecryptFile();    
        }
    public String getbankName() {
//getting bank name logic
}
          @Bean
            public TaskScheduler poolScheduler() {
                ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
                scheduler.setThreadNamePrefix("poolScheduler");
                scheduler.setPoolSize(10);
                return scheduler;
            }   
        @Scheduled(cron = "0 30 5 * * *")
        @Scheduled(cron = "0 0 6 * * *")
        @Scheduled(cron = "0 30 9 * * *")
        @Scheduled(cron = "0 0 10 * * *")
        @Scheduled(cron = "0 30 12 * * *")
        @Scheduled(cron = "0 0 13 * * *")
        @Scheduled(cron = "0 30 15 * * *")
        @Scheduled(cron = "0 0 16 * * *")
        @Scheduled(cron = "0 30 18 * * *")
        @Scheduled(cron = "0 0 19 * * *")
        public void returnFileProcess() {
            paymentDAO = new PaymentDAO();  
            PaymentResponseDecription paymentResponseDecription = new PaymentResponseDecription();   
            List<String> postedFilesNameList = holcimSFTPPool.downloadResponseFile(remotePostedReturnPath,postedMovePath,postedExtension);
            List<String> unpostedFilesNameList = holcimSFTPPool.downloadResponseFile(remoteUnpostedReturnPath,unpostedMovePath,unpostedExtension);  
            for (int i = 0; i < postedFilesNameList.size(); i++) {
                Integer count = 0;
                Boolean successStatus = false;
                schedulerDetails = new SchedulerDetails();
                try {
                    schedulerDetails.setFileType("RETURN");
                    String postedFile = postedFilesNameList.get(i);
                    schedulerDetails.setLastFileName(postedFile);
                    Boolean decryptStatus = decryptFile.decryptedFile(postedFile.trim(), privateKey.trim(),
                            privatePass.trim());
                    if (decryptStatus) {
                        count = paymentResponseDecription.readFile(postedFile + ".txt", loaclReturnFilePath);
                        successStatus = true;
                    } else {
                        GenericExceptionLog.log("Return posted File is not decrypted");
                    }
                    schedulerDetails.setTotalTransaction(count);
                    if (successStatus) {
                        paymentDAO.insertScheduleDetails(schedulerDetails);
                    }
                } catch (Exception e) {
                    GenericExceptionLog.exceptionJava(e,"Return posted  File Processing...", "HolcimSFTPPoolScheduler");
                }
            }
            if(unpostedFilesNameList.size()<1) {
                GenericExceptionLog.log("posted file is not received");
            }
            for(int i =0;i<unpostedFilesNameList.size();i++){
                Integer count = 0;
                Boolean successStatus = false;
                schedulerDetails = new SchedulerDetails();
                try{
                schedulerDetails.setFileType("RETURN");

                String unpostedFile = unpostedFilesNameList.get(i);
                schedulerDetails.setLastFileName(unpostedFile);
                Boolean decryptStatus = decryptFile.decryptedFile(unpostedFile.trim(), privateKey.trim(),
                        privatePass.trim());
                if (decryptStatus) {
                    paymentResponseDecription.readFile(unpostedFile + ".txt", loaclReturnFilePath);
                    successStatus = true;
                } else {
                    GenericExceptionLog.log("Return Unposted File is not decrypted");
                }
                schedulerDetails.setTotalTransaction(count); 
                if (successStatus) {
                    paymentDAO.insertScheduleDetails(schedulerDetails);
                }
                }
                catch(Exception e){
                    GenericExceptionLog.exceptionJava(e, "return unposted file processing.. ","HolcimSFTPPoolScheduler");
                }
                }

            if(unpostedFilesNameList.size()<1) {
                GenericExceptionLog.log("Unposted file is not received");
            }       
        }
    //    Deleted  previous day all Insufficient Funds Transactions 

         @Scheduled(cron = "0 10 0 * * *")
         void deletedAllPreviousDayTransaction (){ 
             GenericExceptionLog.log("Insufficient Funds Batch Start");
             paymentDAO = new PaymentDAO();
             paymentDAO.deletedTransaction();
             GenericExceptionLog.log("Insufficient Funds Batch End");
         }

        @Scheduled(cron = "0 30 4 * * *")
        @Scheduled(cron = "0 30 8 * * *")
        @Scheduled(cron = "0 30 11 * * *")
        @Scheduled(cron = "0 30 14 * * *")
        @Scheduled(cron = "0 30 17 * * *")  
         public void uploadFileProcess() {
            GenericExceptionLog.log("Starting First Batch Timing ::");
            Boolean status = false;
            paymentDAO = new PaymentDAO();
            schedulerDetails = new SchedulerDetails(); 
            try {   
                StringBuffer query = new StringBuffer();
                String seq = getSequence("UPLOAD");
                schedulerDetails.setFileType("UPLOAD");
                schedulerDetails.setSequenceNumber(seq);

                query.append("SELECT ID,REQUEST_PACKET,TRANS_NUMBER,CUSTOMER_CODE,SD_DOC_NO,REF_SO_NO,AMOUNT_TO_PAY ");
                query.append(" FROM PAYMENT_TRANSACTION ");
                query.append(
                        " where uploaded_status =? and ( cast ([scheduleDate] as date) >= CONVERT(date, getdate()-1) and cast ([scheduleDate] as date) <= CONVERT(date, getdate()))");

                List<PaymentRequestPacket> list = paymentDAO.getAllRequestTrasnsactionPacket(query.toString());
                GenericExceptionLog.log("successfully fetch all requested packet ::List is empty" + list.isEmpty());
                if (null != list && !list.isEmpty()) {
                    String fileName = paymentUploadEncription.getFileName(seq) == null ? ""
                            : paymentUploadEncription.getFileName(seq).trim();
                    schedulerDetails.setLastFileName(fileName);
                    paymentUploadEncription = new PaymentUploadEncription(schedulerDetails);
                    schedulerDetails = paymentUploadEncription.formPacket(list, fileName);

                    if (schedulerDetails.getStatus()==null?false:schedulerDetails.getStatus()) {
                        GenericExceptionLog.log("successfully Generated Uploaded File");
                        paymentDAO.insertScheduleDetails(schedulerDetails);

                    } else {
                        GenericExceptionLog.log("Unsuccessfull Uploaded File");
                    }

                }
            } catch (Exception e) {
                GenericExceptionLog.exceptionJava(e, "Batch from Today "+System.currentTimeMillis()+" data to till now :: callSFTPBatchSecond()",
                        "HolcimSFTPPoolScheduler");
            }
        }
        String getSequence(String fileType) {
            paymentDAO = new PaymentDAO();
            SchedulerDetails schedulDetails = paymentDAO.getScheduleDetails(fileType);
            Integer seq = 0;
            if (null != schedulDetails) {
                seq = schedulDetails.getSequenceNumber() == null ? 0 : Integer.parseInt(schedulDetails.getSequenceNumber());
            }
            seq++;
            String sequence = String.format("%03d", seq);
            return sequence;
        }
    }

There are number of ways to do this:有多种方法可以做到这一点:

  • Using @ConditionalOnProperty(value = "jobs.enabled", matchIfMissing = true, havingValue = "true") on your method definition.在您的方法定义上使用@ConditionalOnProperty(value = "jobs.enabled", matchIfMissing = true, havingValue = "true") You can set these values based on your bank name.您可以根据您的银行名称设置这些值。
  • You can create a job profile using @Profile("hdfc")您可以使用@Profile("hdfc")创建工作资料

you can try the org.springframework.scheduling.TaskScheduler in the spring您可以尝试 spring 中的 org.springframework.scheduling.TaskScheduler

     public void scheduleTask(){

    Runnable task = () -> {
        System.out.println("Running scheduled job : " + Thread.currentThread().getName());
    };
    ScheduledFuture<?> scheduledTask = scheduler.schedule(task, new CronTrigger("0 * * ? * *", TimeZone.getTimeZone(TimeZone.getDefault().getID())));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM