Dbms_Scheduler
Oracle 10g 之前,可以使用dbms_job來管理定時任務:
dbms_job.submit(job=>outjob,what=>'pro_name;',next_date=>sysdate,inteval=>'sysdate+1/24');
10g 之後,Oracle 引入了dbms_scheduler 和 program ,在功能方面,它比dbms_job提供了更強大的功能和靈活的機制/管理。
使用dbms_scheduler 創建一個定時任務有兩種形式:
- 創建一個scheduler來定義計劃,一個program來定義任務內容,在創建一個job,爲這個job指定上面的scheduler和program
- 直接創建job,在參數裏面直接指定計劃和任務內容
要執行dbms_scheduler需要create job 權限
select * from dba_sys_privs where grantee=upper('t1'); --dba權限
grant create job to t1 --授權
- 示例
--建立測試表
create table test_t1(id integer,create_date date);
--建立存儲過程
create or replace procedure test_p1
is
v_maxid test_t1.id%type:=1;
begin
select nvl(max(id),0) into v_maxId from test_t1;
insert into test_t1 values(v_maxid,sysdate);
commit;
end test_p1;
--建立作業
declare
v_count int:=0;
begin
select count(*) into v_count from user_scheduler_jobs where job_name=upper('test_job1');
if v_count>0 then
dbms_scheduler.drop_job(upper('test_job1'));
end if;
dbms_scheduler.create_job(
job_name=>'test_job1', --必選 任務名稱
job_type => 'STORED_PROCEDURE',--必須 任務類型【存儲過程,匿名塊等】
job_action=>'TEST_P1',--必須 任務內容,與job_type配合使用
start_date => sysdate, --可選 首次執行時間,爲空時表示立即執行
repeat_interval=>'FREQ=MINUTELY;INTERVAL=1', --可選,執行頻率,爲空時表示只執行一次
--【FREQ=minutely; 表示間隔單位,可選值Yearly,monthly,weekly,datly,hourly,minutely,secondly】
enabled=>true); --可選 是否啓用任務,注意:這裏是enabled;
end;