Oracle-定时任务详情

定时任务可以很好的帮助我们执行一些重复性的工作,比如每天一次或者每周一次的定时表检查,我们根据目的来定义一个JOB去执行我们需要的存储。
那么首先,我们就需要先定义一个需要执行的存储,在JOB中指的就是WAHT()。
创建存储:

create or replace procedure p_ex_cur as 
null_excep exception;--自定义一个异常
class_new1 class_new2%rowtype;--定义一个和class_new的字段类型和名称一样的变量
cursor cur_ex is select * from class_new2;--定义一个显性游标
begin 
  for class_new1 in cur_ex loop --FOR语句循环遍历游标中的数据
    begin -- 开始begin,end嵌套
      if class_new1.class_id is null then --进行if判断
        raise null_excep; -- 抛出异常
        end if;
    exception
      when null_excep then -- 异常抛出之后的操作
        insert into class_new2 (class_te,class_date)values('class_id为空',sysdate);
        commit; 
    end; -- 结束begin,end嵌套
    if class_new1.class_id is not null then
      class_new1.class_id:=f_newid; --将class_id重新赋值
      class_new1.class_date:=sysdate;
      insert into class_new3 values(class_new1.class_id,class_new1.class_name,class_new1.class_te,class_new1.class_date); -- 将读取的游标数据插入到class_new2表;
      commit;
    end if; -- 结束IF
  end loop; -- 结束循环
end;

上述存储是我们在定时任务中调用的存储。
创建定时任务:

declare
  job_number number; -- 定义一个number变量
  job_number1 number; -- 定义一个number变量
  cursor cur_ex is select max(job) from user_jobs; --定义显性游标
begin
  open cur_ex; -- 打开游标
  fetch cur_ex into job_number1; --读取游标
  job_number:=job_number+1; -- 对变量进行赋值(JOB编号不能重复)
  sys.dbms_job.submit(  --创建JOB.submit
    job=>job_number, -- JOB编号
    what=>'p_ex_cur;', -- JOB所执行的存储
    next_date=>sysdate+5/(24*60), -- JOB下次执行的时间
    interval=>'sysdate+1/(24*60)' -- JOB执行的间隔时间
  );
  commit;
end;

到此,我们就创建了一个在5分钟之后,执行间隔为1分钟,执行存储为我们创建的p_ex_cur 的定时任务了。

下面详细介绍下定时JOB的其他功能:
1、暂停调度JOB:

begin
  sys.dbms_job.broken(
    job=>'123',
    broken=>true, -- 定义broken为真,即删除
    next_date=>sysdate+1/(24*60)); --要暂停的时间(一分钟之后)
  commit;
end;

2、运行调度JOB:

begin
  sys.dbms_job.run(
    job=>'123',
    force=>true); 定义force为真,即运行
  commit;
end;

3、修改JOB执行时间间隔:

begin
  sys.dbms_job.interval(
    job=>'123',
    interval=>'sysdate+1/24');--每小时执行一次JOB
  commit;
end;

4、修改JOB下次执行时间:

begin
  sys.dbms_job.next_date(
    job=>'123',
    next_date=>sysdate+1); -- 下次执行时间为第二天
  commit;
end;

5、删除JOB:

begin
  sys.dbms_job.remove(
    job=>'123'); -- 要删除的JOB编号
  commit;
end;

6、修改执行存储:

begin
  sys.dbms_job.what(
    job=>'123',
    what=>'p_ex_cur1;'); -- 要执行的新存储
  commit;
end;

你可能感兴趣的:(Oracle简要学习)