Oracle job не работают

Задание СУБД Oracle не выполняется

Я определил задание, которое будет выполняться со вторника по воскресенье каждые 5 минут. с 9:00 до 22:00

Но работа не проходит проверку

Проверяя задание, все в порядке:

И запустив задание вручную, он выполняет процедуру, но только один раз, а не каждые 5 минут

2 ответа

Это один из наиболее часто задаваемых вопросов Планировщику. Здесь мы перечисляем некоторые из распространенных проблем и способы их решения.

1) job_queue_processes может быть слишком низким (это наиболее распространенная проблема) Значение job_queue_processes ограничивает общее количество dbms_scheduler и задания dbms_job, которые могут выполняться в заданное время. Чтобы проверить, так ли это, проверьте текущее значение job_queue_processes с SQL> выберите значение из параметра v $, где name = ‘job_queue_processes’; Затем проверьте количество запущенных заданий. SQL> выберите количество () из dba_scheduler_running_jobs; SQL> выберите количество () из dba_jobs_running;

Если это проблема, вы можете увеличить параметр, используя SQL> alter system set job_queue_processes = 1000;

2) max_job_slave_processes может быть слишком низким. Если этот параметр не равен NULL, он ограничивает количество заданий dbms_scheduler, которые могут выполняться одновременно. Чтобы проверить, является ли это проблемой, проверьте текущее значение с помощью SQL> выберите значение из dba_scheduler_global_attribute, где attribute_name = ‘MAX_JOB_SLAVE_PROCESSES’; Затем проверьте количество выполняемых заданий. SQL> выберите количество (*) из dba_scheduler_running_jobs;

Если это проблема, вы можете увеличить число или просто обнулить его, используя SQL> exec dbms_scheduler.set_scheduler_attribute (‘max_job_slave_processes’, null)

3) количество сеансов может быть слишком низким. Этот параметр ограничивает количество сеансов в любое время. Для каждого задания планировщика требуется 2 сеанса. Чтобы проверить, является ли это проблемой, проверьте текущее значение с помощью SQL> выберите значение из параметра v $, где name = ‘sessions’; Затем проверьте текущее количество сеансов с помощью SQL> выберите count (*) from v $ session;

Если числа слишком близки, вы можете увеличить максимум, используя SQL> alter system set job_queue_processes = 200;

4) Применяли ли вы недавно патч обновления часового пояса или обновляли ли базу данных до версии с более новой информацией о часовом поясе? Если вы пропустили какие-либо шаги при обновлении информации о часовом поясе, задания могут не выполняться. Чтобы проверить, так ли это, попробуйте выполнить SQL> select * from sys.scheduler $ _job; и SQL> выберите * из sys.scheduler $ _window; и убедитесь, что они закончили без ошибок.

Если он выдает предупреждение о часовом поясе, повторно примените обновление или исправление часового пояса, убедившись, что вы выполнили все шаги.

5) База данных работает в ограниченном режиме? Если база данных работает в ограниченном режиме, никакие задания не будут выполняться (если вы не используете 11g и не используете атрибут ALLOW_RUNS_IN_RESTRICTED_MODE). Чтобы проверить это, используйте SQL> выберите логины из v $ instance;

Если вход в систему ограничен, вы можете отключить ограниченный режим, используя SQL> ALTER SYSTEM DISABLE RESTRICTED SESSION;

6) Запланировано ли выполнение задания на неработающем экземпляре?

Вы можете проверить это, посмотрев, установлен ли instance_id для задания (проверьте представление dba_scheduler_jobs), и если да, то вы должны проверить, запущен ли этот экземпляр.

7) Запланировано ли выполнение задания для службы, которая не была запущена ни на одном экземпляре?

Вы можете проверить это, проверив, на какой job_class указывает задание, а затем проверив, указывает ли этот класс на службу. Если это так, убедитесь, что служба запущена хотя бы на одном работающем экземпляре. Вы можете запустить службу на экземпляре с помощью dbms_service.start_service.

8) Действует ли диспетчер ресурсов с ограниченным планом ресурсов?

Если действует ограничительный план ресурсов, для заданий планировщика может не хватать выделенных ресурсов, поэтому они могут не выполняться. Вы можете проверить, какой план ресурсов действует, выполнив

SQL> выберите имя из V $ RSRC_PLAN;

Если план не действует или действует план INTERNAL_PLAN, то диспетчер ресурсов не действует. Если диспетчер ресурсов действует, вы можете отключить его, выполнив

SQL> изменить системный набор resource_manager_plan = »;

9) Планировщик отключен? Это не поддерживаемое действие, но возможно, что кто-то все равно его выполнил. Чтобы проверить это, выполните SQL> выберите значение из dba_scheduler_global_attribute, где attribute_name = ‘SCHEDULER_DISABLED’

Если этот запрос возвращает TRUE, вы можете исправить это, используя SQL> exec dbms_scheduler.set_scheduler_attribute (‘scheduler_disabled’, ‘false’);

Причины опоздания с вакансиями

1) Первое, что нужно проверить, — это часовой пояс, в котором задание запланировано с помощью SQL> выберите владельца, имя_задания, дату_следующего_пуска из dba_scheduler_jobs;

Если задания находятся в неправильном часовом поясе, они могут не выполняться в ожидаемое время. Если next_run_date использует абсолютное смещение часового пояса (например, +08: 00) вместо именованного часового пояса (например, US / PACIFIC), тогда задания могут выполняться не так, как ожидалось, если действует летнее время — они могут выполняться на час раньше или позже. .

Читайте также:  Сабнатика моды не работают

2) Может случиться так, что в то время, когда задание было запланировано для запуска, одно из нескольких указанных выше ограничений могло быть временно достигнуто, что привело к задержке задания. Убедитесь, что указанные выше пределы достаточно высоки, и, если возможно, проверьте их во время задержки задания.

3) Одна из возможных причин, по которой может быть превышен один из вышеуказанных пределов, заключается в том, что, возможно, вступил в силу интервал обслуживания. Окна обслуживания — это окна планировщика Oracle, которые принадлежат группе окон с именем MAINTENANCE_WINDOW_GROUP. Во время планового окна обслуживания несколько задач обслуживания запускаются с помощью заданий. Это может привести к срабатыванию одного из перечисленных выше ограничений и задержке пользовательских заданий. Дополнительную информацию об этом см. В руководстве администратора (глава 24).

Чтобы получить список окон обслуживания, используйте SQL> выберите * from dba_scheduler_wingroup_members;

Чтобы увидеть, когда запускаются окна, используйте SQL> выберите * from dba_scheduler_windows;

Чтобы исправить это, вы можете увеличить лимиты или перенести окна обслуживания, чтобы они запускались в более удобное время.

Диагностика других проблем

Если ничего из этого не сработает, вот еще несколько шагов, которые вы можете предпринять, чтобы попытаться выяснить, что происходит.

1) Проверьте, нет ли ошибок в журнале предупреждений. Если у базы данных возникли проблемы с выделением памяти, закончилось место на диске или возникли другие катастрофические ошибки, вы должны сначала устранить их. Вы можете найти местоположение журнала предупреждений, используя SQL> выберите значение из параметра v $, где name = ‘background_dump_dest’; Журнал предупреждений будет находиться в этом каталоге с именем, начинающимся с «предупреждения».

2) Проверьте, есть ли файл трассировки координатора заданий, и если он есть, проверьте, содержит ли он какие-либо ошибки. Если он существует, он будет расположен в каталоге ‘background_dump_dest’, который вы можете найти, как указано выше, и будет выглядеть примерно как SID-cjq0_nnnn.trc. Если здесь есть какие-либо ошибки, они могут намекнуть, почему задания не выполняются.

3) Если любое из вышеперечисленных указывает, что табличное пространство SYSAUX (где планировщик хранит свои таблицы журналирования) заполнено, вы можете использовать процедуру dbms_scheduler.purge_log для очистки старых записей журнала.

4) Посмотрите, открыто ли в данный момент окно. Если есть, вы можете попробовать закрыть его, чтобы посмотреть, поможет ли это.

5) попробуйте запустить простое однократное задание и посмотрите, работает ли оно

6) Если простое однократное задание не запускается, вы можете попробовать перезапустить планировщик следующим образом.

В многопользовательской среде контейнер также должен иметь правильное значение для job_queue_processes.

Источник

48 DBMS_JOB

The DBMS_JOB package schedules and manages jobs in the job queue.

The DBMS_JOB package has been superseded by the DBMS_SCHEDULER package. In particular, if you are administering jobs to manage system load, you should consider disabling DBMS_JOB by revoking the package execution privilege for users.

This chapter contains the following topics:

Using DBMS_JOB

Security Model

No specific system privileges are required to use DBMS_JOB . No system privileges are available to manage DBMS_JOB . Jobs cannot be altered or deleted other than jobs owned by the user. This is true for all users including those users granted DBA privileges.

You can execute procedures that are owned by the user or for which the user is explicitly granted EXECUTE . However, procedures for which the user is granted the execute privilege through roles cannot be executed.

Note that, once a job is started and running, there is no easy way to stop the job.

Operational Notes

Working with Real Application Clusters

DBMS_JOB supports multi-instance execution of jobs. By default jobs can be executed on any instance, but only one single instance will execute the job. In addition, you can force instance binding by binding the job to a particular instance. You implement instance binding by specifying an instance number to the instance affinity parameter. Note, however, that in Oracle Database 10g Release 1 (10.1) instance binding is not recommended. Service affinity is preferred. This concept is implemented in the DBMS_SCHEDULER package.

The following procedures can be used to create, alter or run jobs with instance affinity. Note that not specifying affinity means any instance can run the job.

DBMS_JOB.SUBMIT

To submit a job to the job queue, use the following syntax:

Use the parameters instance and force to control job and instance affinity. The default value of instance is 0 (zero) to indicate that any instance can execute the job. To run the job on a certain instance, specify the instance value. Oracle displays error ORA-23319 if the instance value is a negative number or NULL.

Читайте также:  Как узнать работает ли номер билайн или нет если долго не оплачивал

The force parameter defaults to false. If force is TRUE, any positive integer is acceptable as the job instance. If force is FALSE, the specified instance must be running, or Oracle displays error number ORA-23428.

DBMS_JOB.INSTANCE

To assign a particular instance to execute a job, use the following syntax:

The FORCE parameter in this example defaults to FALSE. If the instance value is 0 (zero), job affinity is altered and any available instance can execute the job despite the value of force. If the INSTANCE value is positive and the FORCE parameter is FALSE, job affinity is altered only if the specified instance is running, or Oracle displays error ORA-23428.

If the force parameter is TRUE , any positive integer is acceptable as the job instance and the job affinity is altered. Oracle displays error ORA-23319 if the instance value is negative or NULL .

DBMS_JOB.CHANGE

To alter user-definable parameters associated with a job, use the following syntax:

Two parameters, instance and force, appear in this example. The default value of instance is null indicating that job affinity will not change.

The default value of force is FALSE. Oracle displays error ORA-23428 if the specified instance is not running and error ORA-23319 if the instance number is negative.

DBMS_JOB.RUN

The force parameter for DBMS_JOB.RUN defaults to FALSE. If force is TRUE, instance affinity is irrelevant for running jobs in the foreground process. If force is FALSE , the job can run in the foreground only in the specified instance. Oracle displays error ORA-23428 if force is FALSE and the connected instance is the incorrect instance.

Stopping a Job

Note that, once a job is started and running, there is no easy way to stop the job.

Summary of DBMS_JOB Subprograms

Table 48-1 DBMS_JOB Package Subprograms

Disables job execution

Alters any of the user-definable parameters associated with a job

Assigns a job to be run by a instance

Alters the interval between executions for a specified job

Alters the next execution time for a specified job

Removes specified job from the job queue

Forces a specified job to run

Submits a new job to the job queue

Re-creates a given job for export, or re-creates a given job for export with instance affinity

Alters the job description for a specified job

BROKEN Procedure

This procedure sets the broken flag. Broken jobs are never run.

Table 48-2 BROKEN Procedure Parameters

Subprogram Description

Number of the job being run.

Job broken: IN value is FALSE .

Date of the next refresh.

If you set job as broken while it is running, Oracle resets the job’s status to normal after the job completes. Therefore, only execute this procedure for jobs that are not running.

You must issue a COMMIT statement immediately after the statement.

CHANGE Procedure

This procedure changes any of the fields a user can set in a job.

Table 48-3 CHANGE Procedure Parameters

Parameter Description

Number of the job being run.

PL/SQL procedure to run.

Date of the next refresh.

Date function; evaluated immediately before the job starts running.

When a job is submitted, specifies which instance can run the job. This defaults to NULL , which indicates that instance affinity is not changed.

If this is FALSE , then the specified instance (to which the instance number change) must be running. Otherwise, the routine raises an exception.

If this is TRUE , then any positive integer is acceptable as the job instance.

You must issue a COMMIT statement immediately after the statement.

The parameters instance and force are added for job queue affinity. Job queue affinity gives users the ability to indicate whether a particular instance or any instance can run a submitted job.

If the parameters what , next_date , or interval are NULL , then leave that value as it is.

I NSTANCE Procedure

This procedure changes job instance affinity.

Table 48-4 INSTANCE Procedure Parameters

Parameter Description

Number of the job being run.

When a job is submitted, a user can specify which instance can run the job.

If this is TRUE , then any positive integer is acceptable as the job instance. If this is FALSE (the default), then the specified instance must be running; otherwise the routine raises an exception.

You must issue a COMMIT statement immediately after the statement.

INTERVAL Procedure

This procedure changes how often a job runs.

Table 48-5 INTERVAL Procedure Parameters

Parameter Description

Number of the job being run.

Date function, evaluated immediately before the job starts running.

If the job completes successfully, then this new date is placed in next_date . interval is evaluated by plugging it into the statement select interval into next_date from dual;

The interval parameter must evaluate to a time in the future. Legal intervals include:

Parameter Description
Interval Description
‘sysdate + 7’ Run once a week.
‘next_day(sysdate,»TUESDAY»)’ Run once every Tuesday.
‘null’ Run only once.

If interval evaluates to NULL and if a job completes successfully, then the job is automatically deleted from the queue.

You must issue a COMMIT statement immediately after the statement.

NEXT_DATE Procedure

This procedure changes when an existing job next runs.

Table 48-6 NEXT_DATE Procedure Parameters

Number of the job being run.

Date of the next refresh: it is when the job will be automatically run, assuming there are background processes attempting to run it.

You must issue a COMMIT statement immediately after the statement.

REMOVE Procedure

This procedure removes an existing job from the job queue. This currently does not stop a running job.

Table 48-7 REMOVE Procedure Parameters

Parameter Description

Number of the job being run.

You must issue a COMMIT statement immediately after the statement.

RUN Procedure

This procedure runs job JOB now. It runs it even if it is broken.

Running the job recomputes next_date . See view user_jobs .

Table 48-8 RUN Procedure Parameters

Parameter Description

Number of the job being run.

If this is TRUE , then instance affinity is irrelevant for running jobs in the foreground process. If this is FALSE , then the job can be run in the foreground only in the specified instance.

This re-initializes the current session’s packages.

An exception is raised if force is FALSE , and if the connected instance is the wrong one.

SUBMIT Procedure

This procedure submits a new job. It chooses the job from the sequence sys . jobseq .

Table 48-9 SUBMIT Procedure Parameters

Parameter Description

Number of the job being run.

PL/SQL procedure to run.

Next date when the job will be run.

Date function that calculates the next time to run the job. The default is NULL . This must evaluate to a either a future point in time or NULL .

A flag. The default is FALSE . If this is set to FALSE , then Oracle parses the procedure associated with the job. If this is set to TRUE , then Oracle parses the procedure associated with the job the first time that the job is run.

For example, if you want to submit a job before you have created the tables associated with the job, then set this to TRUE .

When a job is submitted, specifies which instance can run the job.

If this is TRUE , then any positive integer is acceptable as the job instance. If this is FALSE (the default), then the specified instance must be running; otherwise the routine raises an exception.

You must issue a COMMIT statement immediately after the statement.

The parameters instance and force are added for job queue affinity. Job queue affinity gives users the ability to indicate whether a particular instance or any instance can run a submitted job.

This submits a new job to the job queue. The job calls the procedure DBMS_DDL . ANALYZE_OBJECT to generate optimizer statistics for the table DQUON . ACCOUNTS . The statistics are based on a sample of half the rows of the ACCOUNTS table. The job is run every 24 hours:

USER_EXPORT Procedures

There are two overloaded procedures. The first produces the text of a call to re-create the given job. The second alters instance affinity (8 i and after) and preserves the compatibility.

Table 48-10 USER_EXPORT Procedure Parameter

Parameter Description

Number of the job being run.

Text of a call to re-create the given job.

Text of a call to alter instance affinity.

WHAT Procedure

This procedure changes what an existing job does, and replaces its environment.

Table 48-11 WHAT Procedure Parameters

Parameter Description

Number of the job being run.

PL/SQL procedure to run.

You must issue a COMMIT statement immediately after the statement.

Some legal values of what (assuming the routines exist) are:

‘myproc(»10-JAN-82», next_date, broken);’

Источник

Оцените статью
Parameter Description