[SAP ABAP开发技术总结]程序自己以JOB方式运行
该程序在运行时会创建一个JOB,并且将该自己以JOB后台方式运行,并且可以从前台传递参数到后台JOB
REPORT ymais_sust.
TABLES vbap.
PARAMETERS: p_back .
SELECT-OPTIONS: s_vbeln FOR vbap-vbeln .
DATA: l_number TYPE tbtcjob-jobcount,
l_name TYPE tbtcjob-jobname .
DATA: run_flg."当前程序是否已在后台运行过了
l_name = sy-repid."当前程序名
START-OF-SELECTION.
DATA: c_tmp(20).
DATA:l_jobcount TYPE tbtcm-jobcount,
l_jobname TYPE tbtcm-jobname.
"如果当前程序是在后台运行时,从SAP内存中读取前台共享的参数
IF sy-batch IS NOT INITIAL.
CALL FUNCTION 'GET_JOB_RUNTIME_INFO'"获取当前后台Job名与Job编号
IMPORTING
jobcount = l_jobcount
jobname = l_jobname.
CONCATENATE 'YMAIS_SUST' l_jobcount INTO c_tmp RESPECTING BLANKS.
"读取从前台传递过来的参数
IMPORT run_flg FROM SHARED BUFFER indx(fi) ID c_tmp.
IF sy-subrc <> 0.
MESSAGE e001(00) WITH 'import data unsuccessful'.
ELSE.
"所有输出的 message 可以在假脱机日志里看到
MESSAGE i001(00) WITH '从前台读取来的值 run_flg = ' run_flg.
"共享内存使用后即时删除,否则要等到服务器重启再消失
DELETE FROM SHARED BUFFER indx(fi) ID c_tmp.
ENDIF.
ELSE."如果是通过前台运行时
CALL FUNCTION 'JOB_OPEN'
EXPORTING
jobname = l_name
IMPORTING
jobcount = l_number
EXCEPTIONS
cant_create_job = 1
invalid_job_data = 2
jobname_missing = 3
OTHERS = 4.
IF sy-subrc = 0.
"直接采用 SUBMIT 的方式,让报表程序在后台运行
SUBMIT ymais_sust
WITH p_back = p_back"Paramters参数
WITH s_vbeln IN s_vbeln"Selection-option参数
* WITH s_bukrs BETWEEN '1106' AND '1111' SIGN 'I'"如果Selection-option只有一行时,可以这样使用,如果是单个值,还可以这样使用:
* WITH bukrs eq '1106' SIGN 'I'
VIA JOB l_name NUMBER l_number AND RETURN.
"由于 Shared Buffer是整个服务器都可以共享的,所以每个后台Job需要自己的 Buffer,所以
"使用各自Job的编号来区分。该方式用来在前台程序与后台Job之间传递参数
CONCATENATE 'YMAIS_SUST' l_number INTO c_tmp RESPECTING BLANKS.
EXPORT run_flg FROM 'X' TO SHARED BUFFER indx(fi) ID c_tmp.
"也可以通过下面标准函数来提交Job,但此标准函数不能直接将前台参数传递给后台Job程序(除通过变式
"参数 VARIANT 外)。所以只能采用上面 EXPORT ... SHARED BUFFER 语句来共享服务器内存来实现
* CALL FUNCTION 'JOB_SUBMIT'
* EXPORTING
* authcknam = sy-uname
* jobcount = l_number
* jobname = l_name
** PRIPARAMS = ' '打印参数
* report = 'YMAIS_SUST'
** VARIANT = ' '可通过变式来传递参数
CALL FUNCTION 'JOB_CLOSE'
EXPORTING
jobcount = l_number
jobname = l_name
strtimmed = 'X'.
ENDIF.
ENDIF.
END-OF-SELECTION.
"如果当前程序是在后台运行时
IF sy-batch IS NOT INITIAL.
"会输出到假脱机输出列表中
WRITE: / '后台输出'.
"后面还可以写在后台运行时需要执行的代码逻辑及输出
......
ELSE.
MESSAGE '当前程序已经通过后台运行' TYPE 'I'.
LEAVE PROGRAM.
ENDIF.