Schedule a task with Cron which allows dynamic update

后端 未结 2 527
野性不改
野性不改 2021-02-06 00:47

I use sprint boot 1.3, spring 4.2

In this class

@Service
public class PaymentServiceImpl implements PaymentService {
    ....
    @Transactional
    @Ove         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-06 01:28

    Just if someone still having this issue a better solution getting value from database whenever you want without many changes would be run cron every minute and get mod between current minute versus a configurated value delta from database, if this mod is equals to 0 means it has to run like if it is a mathematical multiple, so if you want it to run every 5 minutes for example delta should be 5.

    A sample:

    @Scheduled(cron = "0 */1 * * * *") //fire every minute
    public void perform() {
    
        //running
        Integer delta = 5;//get this value from databse
        Integer minutes = getField(Calendar.MINUTE)//calendar for java 7;
        Boolean toRun = true;//you can also get this one from database to make it active or disabled
      
        toRun = toRun && (minutes % delta == 0);
        if (toRun && (!isRunning)) {
           isRunning = true;
           try {
             //do your logic here
           } catch (Exception e) { }
            isRunning = false;
        }
    }
    
    public Integer getField(int field) {
    
        Calendar now = Calendar.getInstance();
    
        if(field == Calendar.MONTH) {
            return now.get(field)+ 1; // Note: zero based!
        }else {
            return now.get(field);
        }
    }
    

    Hope this help :D

提交回复
热议问题