Java stop scheduled task if it takes more than a specific time












0















I have a scheduled job which runs every 100 seconds. Sometimes the execution of this method takes a lot of time (which is ok and there is no problem with that). In this situation, the result of the running method is not important to me and I want to re-schedule the job for next 100 second.



What is the best way to force the running job to terminate (return) after a specific time?



My scheduled code is like below:



@Scheduled(fixedDelay = 100*1000)
fun calculateLastDaysStatistics() {
logger.info("affiliate statistics thread Started Successfully")
val processStartDate = Date()

for (i in 1..prevDaysToConsider) {
logger.info("AdZone-Stats prev days $i")

val yesterday = DateUtility.addDay(Date(), -i)

val startDate = DateUtility.getZeroDayTime(yesterday.time)
val endDate = DateUtility.addDay(startDate, 1)

/* This method is probable to take a lot of time */
calculateStatistics(startDate, endDate)
}

val processLength = (Date().time - processStartDate.time) / 1000
logger.info("affiliate statistics thread finished in " + processLength + "s")
}


Thanks.










share|improve this question



























    0















    I have a scheduled job which runs every 100 seconds. Sometimes the execution of this method takes a lot of time (which is ok and there is no problem with that). In this situation, the result of the running method is not important to me and I want to re-schedule the job for next 100 second.



    What is the best way to force the running job to terminate (return) after a specific time?



    My scheduled code is like below:



    @Scheduled(fixedDelay = 100*1000)
    fun calculateLastDaysStatistics() {
    logger.info("affiliate statistics thread Started Successfully")
    val processStartDate = Date()

    for (i in 1..prevDaysToConsider) {
    logger.info("AdZone-Stats prev days $i")

    val yesterday = DateUtility.addDay(Date(), -i)

    val startDate = DateUtility.getZeroDayTime(yesterday.time)
    val endDate = DateUtility.addDay(startDate, 1)

    /* This method is probable to take a lot of time */
    calculateStatistics(startDate, endDate)
    }

    val processLength = (Date().time - processStartDate.time) / 1000
    logger.info("affiliate statistics thread finished in " + processLength + "s")
    }


    Thanks.










    share|improve this question

























      0












      0








      0








      I have a scheduled job which runs every 100 seconds. Sometimes the execution of this method takes a lot of time (which is ok and there is no problem with that). In this situation, the result of the running method is not important to me and I want to re-schedule the job for next 100 second.



      What is the best way to force the running job to terminate (return) after a specific time?



      My scheduled code is like below:



      @Scheduled(fixedDelay = 100*1000)
      fun calculateLastDaysStatistics() {
      logger.info("affiliate statistics thread Started Successfully")
      val processStartDate = Date()

      for (i in 1..prevDaysToConsider) {
      logger.info("AdZone-Stats prev days $i")

      val yesterday = DateUtility.addDay(Date(), -i)

      val startDate = DateUtility.getZeroDayTime(yesterday.time)
      val endDate = DateUtility.addDay(startDate, 1)

      /* This method is probable to take a lot of time */
      calculateStatistics(startDate, endDate)
      }

      val processLength = (Date().time - processStartDate.time) / 1000
      logger.info("affiliate statistics thread finished in " + processLength + "s")
      }


      Thanks.










      share|improve this question














      I have a scheduled job which runs every 100 seconds. Sometimes the execution of this method takes a lot of time (which is ok and there is no problem with that). In this situation, the result of the running method is not important to me and I want to re-schedule the job for next 100 second.



      What is the best way to force the running job to terminate (return) after a specific time?



      My scheduled code is like below:



      @Scheduled(fixedDelay = 100*1000)
      fun calculateLastDaysStatistics() {
      logger.info("affiliate statistics thread Started Successfully")
      val processStartDate = Date()

      for (i in 1..prevDaysToConsider) {
      logger.info("AdZone-Stats prev days $i")

      val yesterday = DateUtility.addDay(Date(), -i)

      val startDate = DateUtility.getZeroDayTime(yesterday.time)
      val endDate = DateUtility.addDay(startDate, 1)

      /* This method is probable to take a lot of time */
      calculateStatistics(startDate, endDate)
      }

      val processLength = (Date().time - processStartDate.time) / 1000
      logger.info("affiliate statistics thread finished in " + processLength + "s")
      }


      Thanks.







      java spring-boot kotlin






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 18:29









      hamid ghasemihamid ghasemi

      6812725




      6812725
























          2 Answers
          2






          active

          oldest

          votes


















          1














          Try using Fixed Rate instead of Fixed Delay



          Here is the article from
          Paraschiv.E. The @Scheduled Annotation in Spring. Referred from https://www.baeldung.com/spring-scheduled-tasks







          1. Schedule a Task at a Fixed Rate



            @Scheduled(fixedRate = 1000)
            public void scheduleFixedRateTask() {
            System.out.println(
            "Fixed rate task - " + System.currentTimeMillis() / 1000);
            }




          Note that the beginning of the task execution doesn’t wait for the completion of the previous execution.



          This option should be used when each execution of the task is independent.






          share|improve this answer
























          • Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

            – hamid ghasemi
            Jan 2 at 19:40











          • I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

            – Basil Bourque
            Jan 2 at 19:42













          • @BasilBourque you're right and in this situation again I can not get the next run's results on time.

            – hamid ghasemi
            Jan 3 at 6:54






          • 1





            @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

            – Basil Bourque
            Jan 3 at 7:19





















          0














          You can implement a custom Task scheduler using, org.springframework.scheduling.TaskScheduler instead of Annotation based method.



          private final TaskScheduler scheduler;

          @Autowired
          public SchedulingManager(TaskScheduler scheduler) {
          this.scheduler = scheduler;
          }


          In this case,



          ScheduledFuture scheduledeFuture =  scheduler.schedule(()->{
          ....You job goes here..

          }, new CronTrigger("*/100 * * * * *"));


          You can keep track of the scheduled future to make sure it runs max time intended.



          scheduledeFuture.get(100,TimeUnit.SECONDS)





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54011385%2fjava-stop-scheduled-task-if-it-takes-more-than-a-specific-time%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Try using Fixed Rate instead of Fixed Delay



            Here is the article from
            Paraschiv.E. The @Scheduled Annotation in Spring. Referred from https://www.baeldung.com/spring-scheduled-tasks







            1. Schedule a Task at a Fixed Rate



              @Scheduled(fixedRate = 1000)
              public void scheduleFixedRateTask() {
              System.out.println(
              "Fixed rate task - " + System.currentTimeMillis() / 1000);
              }




            Note that the beginning of the task execution doesn’t wait for the completion of the previous execution.



            This option should be used when each execution of the task is independent.






            share|improve this answer
























            • Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

              – hamid ghasemi
              Jan 2 at 19:40











            • I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

              – Basil Bourque
              Jan 2 at 19:42













            • @BasilBourque you're right and in this situation again I can not get the next run's results on time.

              – hamid ghasemi
              Jan 3 at 6:54






            • 1





              @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

              – Basil Bourque
              Jan 3 at 7:19


















            1














            Try using Fixed Rate instead of Fixed Delay



            Here is the article from
            Paraschiv.E. The @Scheduled Annotation in Spring. Referred from https://www.baeldung.com/spring-scheduled-tasks







            1. Schedule a Task at a Fixed Rate



              @Scheduled(fixedRate = 1000)
              public void scheduleFixedRateTask() {
              System.out.println(
              "Fixed rate task - " + System.currentTimeMillis() / 1000);
              }




            Note that the beginning of the task execution doesn’t wait for the completion of the previous execution.



            This option should be used when each execution of the task is independent.






            share|improve this answer
























            • Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

              – hamid ghasemi
              Jan 2 at 19:40











            • I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

              – Basil Bourque
              Jan 2 at 19:42













            • @BasilBourque you're right and in this situation again I can not get the next run's results on time.

              – hamid ghasemi
              Jan 3 at 6:54






            • 1





              @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

              – Basil Bourque
              Jan 3 at 7:19
















            1












            1








            1







            Try using Fixed Rate instead of Fixed Delay



            Here is the article from
            Paraschiv.E. The @Scheduled Annotation in Spring. Referred from https://www.baeldung.com/spring-scheduled-tasks







            1. Schedule a Task at a Fixed Rate



              @Scheduled(fixedRate = 1000)
              public void scheduleFixedRateTask() {
              System.out.println(
              "Fixed rate task - " + System.currentTimeMillis() / 1000);
              }




            Note that the beginning of the task execution doesn’t wait for the completion of the previous execution.



            This option should be used when each execution of the task is independent.






            share|improve this answer













            Try using Fixed Rate instead of Fixed Delay



            Here is the article from
            Paraschiv.E. The @Scheduled Annotation in Spring. Referred from https://www.baeldung.com/spring-scheduled-tasks







            1. Schedule a Task at a Fixed Rate



              @Scheduled(fixedRate = 1000)
              public void scheduleFixedRateTask() {
              System.out.println(
              "Fixed rate task - " + System.currentTimeMillis() / 1000);
              }




            Note that the beginning of the task execution doesn’t wait for the completion of the previous execution.



            This option should be used when each execution of the task is independent.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 2 at 18:48









            bachkilanbachkilan

            112




            112













            • Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

              – hamid ghasemi
              Jan 2 at 19:40











            • I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

              – Basil Bourque
              Jan 2 at 19:42













            • @BasilBourque you're right and in this situation again I can not get the next run's results on time.

              – hamid ghasemi
              Jan 3 at 6:54






            • 1





              @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

              – Basil Bourque
              Jan 3 at 7:19





















            • Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

              – hamid ghasemi
              Jan 2 at 19:40











            • I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

              – Basil Bourque
              Jan 2 at 19:42













            • @BasilBourque you're right and in this situation again I can not get the next run's results on time.

              – hamid ghasemi
              Jan 3 at 6:54






            • 1





              @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

              – Basil Bourque
              Jan 3 at 7:19



















            Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

            – hamid ghasemi
            Jan 2 at 19:40





            Thanks for response, but there are 2 problems with this solution. First of all, long running tasks will not terminate and they can allocate Ram and processor. Secondly, the long running tasks may manipulate data during the execution and therefore it changes the result of other tasks. Ao it is important to terminate other running tasks.

            – hamid ghasemi
            Jan 2 at 19:40













            I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

            – Basil Bourque
            Jan 2 at 19:42







            I suggest testing as that article is incorrect if this Spring feature is actually wrapping ScheduledExecutorService. That doc says a late running task causes subsequent runs to wait, not allowing concurrent runs.

            – Basil Bourque
            Jan 2 at 19:42















            @BasilBourque you're right and in this situation again I can not get the next run's results on time.

            – hamid ghasemi
            Jan 3 at 6:54





            @BasilBourque you're right and in this situation again I can not get the next run's results on time.

            – hamid ghasemi
            Jan 3 at 6:54




            1




            1





            @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

            – Basil Bourque
            Jan 3 at 7:19







            @hamidghasemi As I understand ScheduledExecutorService neither scheduleAtFixedRate​ nor scheduleWithFixedDelay​ supports runs of the task being concurrent. Both are designed to execute runs of the task only in succession, the next one starting only after the previous one completes. The only difference is in how long to wait after completion. I avoid Spring, so I am merely guessing/assuming that this Spring feature wraps a ScheduledExecutorService, but I do not know.

            – Basil Bourque
            Jan 3 at 7:19















            0














            You can implement a custom Task scheduler using, org.springframework.scheduling.TaskScheduler instead of Annotation based method.



            private final TaskScheduler scheduler;

            @Autowired
            public SchedulingManager(TaskScheduler scheduler) {
            this.scheduler = scheduler;
            }


            In this case,



            ScheduledFuture scheduledeFuture =  scheduler.schedule(()->{
            ....You job goes here..

            }, new CronTrigger("*/100 * * * * *"));


            You can keep track of the scheduled future to make sure it runs max time intended.



            scheduledeFuture.get(100,TimeUnit.SECONDS)





            share|improve this answer




























              0














              You can implement a custom Task scheduler using, org.springframework.scheduling.TaskScheduler instead of Annotation based method.



              private final TaskScheduler scheduler;

              @Autowired
              public SchedulingManager(TaskScheduler scheduler) {
              this.scheduler = scheduler;
              }


              In this case,



              ScheduledFuture scheduledeFuture =  scheduler.schedule(()->{
              ....You job goes here..

              }, new CronTrigger("*/100 * * * * *"));


              You can keep track of the scheduled future to make sure it runs max time intended.



              scheduledeFuture.get(100,TimeUnit.SECONDS)





              share|improve this answer


























                0












                0








                0







                You can implement a custom Task scheduler using, org.springframework.scheduling.TaskScheduler instead of Annotation based method.



                private final TaskScheduler scheduler;

                @Autowired
                public SchedulingManager(TaskScheduler scheduler) {
                this.scheduler = scheduler;
                }


                In this case,



                ScheduledFuture scheduledeFuture =  scheduler.schedule(()->{
                ....You job goes here..

                }, new CronTrigger("*/100 * * * * *"));


                You can keep track of the scheduled future to make sure it runs max time intended.



                scheduledeFuture.get(100,TimeUnit.SECONDS)





                share|improve this answer













                You can implement a custom Task scheduler using, org.springframework.scheduling.TaskScheduler instead of Annotation based method.



                private final TaskScheduler scheduler;

                @Autowired
                public SchedulingManager(TaskScheduler scheduler) {
                this.scheduler = scheduler;
                }


                In this case,



                ScheduledFuture scheduledeFuture =  scheduler.schedule(()->{
                ....You job goes here..

                }, new CronTrigger("*/100 * * * * *"));


                You can keep track of the scheduled future to make sure it runs max time intended.



                scheduledeFuture.get(100,TimeUnit.SECONDS)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 3 at 6:32









                aravindaMaravindaM

                643612




                643612






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54011385%2fjava-stop-scheduled-task-if-it-takes-more-than-a-specific-time%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith