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:
in SM36, define a new background job Z_TEST_JOB, click Start condition button:
Maintain the event name ZTEST_EVENT:
Click Step button, maintain the program name which is to be executed in the background.
After step maintenance is finished you could see the information message in SM36.
Write the program to start the background job:
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.
Click the Spool button and we could see the list output via WRITE statement.
Approach 2
Use the function module JOB_OPEN and JOB_CLOSE in launcher program:
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:
The job number could be found also in SM37:
For me I prefer the first approach as it decouples the background program and the launcher program.