Quantcast
Channel: SCN : All Content - ABAP Development
Viewing all articles
Browse latest Browse all 8332

Two ways to start background job via code

$
0
0

Suppose we have a simple program ZBACKGROUND_TASK which needs to be executed in the background.

 

It has only one statement: WRITE: / 'Hello I am running in background!'.

 

 

Approach 1

 

Create a new user event via tcode SM62:

clipboard1.png


in SM36, define a new background job Z_TEST_JOB, click Start condition button:

clipboard2.png

Maintain the event name ZTEST_EVENT:

clipboard3.png

Click Step button, maintain the program name which is to be executed in the background.

clipboard4.png

After step maintenance is finished you could see the information message in SM36.

clipboard5.png

Write the program to start the background job:

 

 

CALL FUNCTION 'BP_EVENT_RAISE'

  EXPORTING

    eventid                = 'ZTEST_EVENT'

  EXCEPTIONS

    bad_eventid            = 1

    eventid_does_not_exist = 2

    eventid_missing        = 3

    raise_failed           = 4

    OTHERS                 = 5.

IF sy-subrc <> 0.

  WRITE: 'Event failed to trigger'.

ELSE.

  WRITE: 'Event triggered'.

ENDIF.

 

 

Once executed, check job status in SM37, it is in finished status.

clipboard7.png


Click the Spool button and we could see the list output via WRITE statement.

clipboard8.png

Approach 2

Use the function module JOB_OPEN and JOB_CLOSE in launcher program:

 

 

DATA: number TYPE tbtcjob-jobcount,

      name   TYPE tbtcjob-jobname VALUE 'JOB_VIA_CODE'.

CALL FUNCTION 'JOB_OPEN'

  EXPORTING

    jobname          = name

  IMPORTING

    jobcount         = number

  EXCEPTIONS

    cant_create_job  = 1

    invalid_job_data = 2

    jobname_missing  = 3

    OTHERS           = 4.

WRITE:/ 'Generated job number: ', number.

IF sy-subrc = 0.

  SUBMIT zbackgroud VIA JOB name NUMBER number AND RETURN.

  IF sy-subrc = 0.

    CALL FUNCTION 'JOB_CLOSE'

      EXPORTING

        jobcount             = number

        jobname              = name

        strtimmed            = 'X'

      EXCEPTIONS

        cant_start_immediate = 1

        invalid_startdate    = 2

        jobname_missing      = 3

        job_close_failed     = 4

        job_nosteps          = 5

        job_notex            = 6

        lock_failed          = 7

        OTHERS               = 8.

    IF sy-subrc <> 0.

      WRITE:/ 'job close Error!'.

    ENDIF.

  ENDIF.

ENDIF.

 

 

Once executed it returns the job number 04175800:

clipboard9.png


The job number could be found also in SM37:

clipboard10.png

clipboard11.png

For me I prefer the first approach as it decouples the background program and the launcher program.


Viewing all articles
Browse latest Browse all 8332

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>