Announcement Announcement Module
Collapse
No announcement yet.
Need to Gracefully Stop the Tasklet Job Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Need to Gracefully Stop the Tasklet Job

    I want to gracefully stop the job. Getting Null Pointer Exception when I tried to get the instance of the JobInstance. I have blocked it in the execute menthod, please find below

    My command line argument is (through eclipse), After giving the stop the job keeps on running.

    -stop broadCastEmailBatchJob.xml emailBroadcastjob status=stops

    Here is the job config


    <bean id="emailBroadcast" class="com.wellsfargo.ccer.batch.broadcast.BroadCa stEmail" scope="step">
    <property name="message" value="Sent111111111111111111111111111111111"/>
    <property name="status" value="#{jobParameters['status']}"/>
    </bean>

    <batch:job id="emailBroadcastjob" job-repository="jobRepository" restartable="true">
    <batch:step id="step0" >
    <batch:tasklet ref="emailBroadcast" transaction-manager="jobRepository-transactionManager">

    </batch:tasklet>
    </batch:step>
    </batch:job>

    Here is the execute method

    public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception
    {

    logger.debug("Starting Point--->");
    System.out.print(message);
    try{

    System.out.println("Status--->" + getStatus());
    initialize();
    if(getStatus().trim().equals("stops")){
    List<BroabcastEmailBo> emailList = getEmailList();
    logger.debug("List from Email list count-->" + emailList.size());
    logger.debug("Ending Point--->");
    System.out.println("str--->" + jobInstance.getJobParameters());
    }
    else{
    Set<Long> list = jobOperator.getRunningExecutions("emailBroadcastjo b");
    jobOperator.stop(list.iterator().next());
    //return RepeatStatus.FINISHED;

    }
    }
    catch(Exception e){
    System.out.print(e.toString());


    }

  • #2
    please use [ CODE ] [ /CODE ] tags.

    first, I'm not sure the JobOperator.stop() method is supposed to be used from within a job, but more from an external component.

    second, if you want to stop a job execution from within the job, you can:
    - throw an exception
    - return a RepeatStatus.FINISHED from the tasklet.

    don't forget the <end />/<stop /> tags that can be useful too. I don't really get what your use case is, but you should perhaps take a look at the reference documentation, which is quite complete on the ways to stop an execution.

    Comment


    • #3
      Thanks Arno for the immediate reply

      Can you provide the sample code for throwing the exception.

      And For gracefull stopping the Job. How is it possible to stop a job from another job. Please provide the sample code..

      Comment


      • #5
        Thanks for the reply.

        Looks like stopping the job cannot be done using Memory Repository. Please confirm. Went through the reference documention , could not find anything done in memory repository. I am having another thread running in this forum to resolve the "DB repository not working" . Once it is done will start this usecase.

        Appreciate all your support.

        Comment


        • #6
          Thil, things get complicated because (depending on configuration) jobs can be launched in a separate thread. So there is no legal way to terminate gracefully the job from another thread (and we want to do it gracefully, because job should be marked as e.g. "FAILED"). The job components (e.g. item reader) should be programmed in a way to support termination on certain conditions by e.g. throwing the exception. Then you need a way to communicate the termination condition to the job (via the shared state object [requester and the job are in same JVM] or via the DB [different JVMs]) and the job will terminate e.g. at the beginning of next read cycle.

          Comment


          • #7
            Now I am able to use the DB repository.

            When I run the same job more than once I am getting the below exception in the spring batch framework.

            Code:
            2011-03-28 11:49:21,606 [main] DEBUG - Returning JDBC Connection to DataSource
            2011-03-28 11:49:21,606 [main] ERROR - Job Terminated in error: A job execution for this job is already running: JobInstance: id=7, JobParameters=[{status=start, time=new}], Job=[emailBroadcastjob]
            org.springframework.batch.core.repository.JobExecutionAlreadyRunningException: A job execution for this job is already running: JobInstance: id=7, JobParameters=[{status=start, time=new}], Job=[emailBroadcastjob]
            	at org.springframework.batch.core.repository.support.SimpleJobRepository.createJobExecution(SimpleJobRepository.java:112)
            	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            	at java.lang.reflect.Method.invoke(Method.java:585)
            	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
            	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
            	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
            	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
            	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
            	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
            	at $Proxy0.createJobExecution(Unknown Source)
            	at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:98)
            	at org.springframework.batch.core.launch.support.CommandLineJobRunner.start(CommandLineJobRunner.java:291)
            	at org.springframework.batch.core.launch.support.CommandLineJobRunner.main(CommandLineJobRunner.java:448)
            2011-03-28 11:49:21,606 [main] INFO - Closing org.springframework.context.support.ClassPathXmlApplicationContext@1d009b4: display name [org.springframework.context.support.ClassPathXmlApplicationContext@1d009b4]; startup date [Mon Mar 28 11:49:19 PDT 2011]; root of context hierarchy
            2011-03-28 11:49:21,606 [main] INFO - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1d1e730: defining beans [jobRepository-dataSource,jobRepository-transactionManager,jobRepository,jobLauncher,emailBroadcast,org.springframework.batch.core.scope.internalStepScope,org.springframework.beans.factory.config.CustomEditorConfigurer,org.springframework.batch.core.configuration.xml.CoreNamespacePostProcessor,step0,emailBroadcastjob,lazyBindingProxy.emailBroadcast]; root of factory hierarchy
            This exception is occuring before it enters into the developer code. Now I need to catch this exception in the below code. Please let me know the sample code
            Code:
            public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws JobExecutionAlreadyRunningException 
            	{
            		
            		logger.debug("Starting Point--->");
            		System.out.print(message); 	
            		try{
            			System.out.println("Status--->" + getStatus());
            			initialize();
            			if(!(getStatus().trim().equals("stops12"))){
            			List<BroabcastEmailBo> emailList = getEmailList();
            			logger.debug("List from Email list count-->" + emailList.size());
            			logger.debug("Ending Point--->");
            			return RepeatStatus.CONTINUABLE; 
            			}
            			else{
            				logger.debug("Stopping the job-------->Start");
            				Set<Long> list =  jobOperator.getRunningExecutions("emailBroadcastjob");
            				jobOperator.stop(list.iterator().next()); 
            				logger.debug("Stopping the job-------->End");
            				return RepeatStatus.FINISHED;
            				
            			}
            		}
            		catch(JobExecutionAlreadyRunningException e){
            			logger.debug("JOb is already running---->");
            		}
            		catch(Exception e2){
            			
            		}
            		if(getStatus().trim().equals("stops")){
            			return RepeatStatus.CONTINUABLE; 
            		}else{
            		  return RepeatStatus.FINISHED;
            		}
            	}
            Here is the command line argument (through Eclipse)
            Code:
            -stop broadCastEmailBatchJob.xml emailBroadcastjob status=stops

            Comment


            • #8
              Hello ALL,

              Can anyone please reply on how to implement the Gracefull stop. In the previous message , I have given full details of what I have done. It will be nice if I get a sample working code. here is what I have coded in thye tasklet

              Code:
              public RepeatStatus execute_m(StepContribution arg0, ChunkContext arg1) throws Exception 
              	{
              		logger.debug("Starting Point--->");
              		System.out.print(message); 	
              		try{
              			Set<String> list =  jobOperator.getJobNames();
              			System.out.println(list.size());	
              		}
              		
              		catch(Exception e2){
              			logger.debug(e2.toString());
              		}
              		if(getStatus().trim().equals("stops")){
              			return RepeatStatus.CONTINUABLE; 
              		}else{
              		  return RepeatStatus.FINISHED;
              		}
              	}
              I am getting Null Pointer Exception in the below line

              Set<String> list = jobOperator.getJobNames();

              Please let me know the solution ASAP.

              Comment


              • #9
                perhaps you didn't inject the jobOperator in the tasklet (if you get a NullPointerException).

                again, I don't see the point of stopping a job from within another job. Just using the job operator from any Java program should work (as long as you use the persistent job repository if from another process).

                BTW, I'm not sure about the syntax you're using to stop the job, you mentioned this in a previous, which looks incorrect (following the Javadoc of the CommandLineJobRunner):
                Code:
                -stop broadCastEmailBatchJob.xml emailBroadcastjob status=stops
                The syntax would be instead:
                Code:
                broadCastEmailBatchJob.xml -stop emailBroadcastjob param1=value1 param2=value2
                remember the job parameters (at the end) determine the running execution of the instance you want to stop.

                Comment

                Working...
                X