1c background tasks. Routine and background tasks. Background and scheduled task - what is it and where is it configured?

1 Job mechanism
2 Background jobs
3 Scheduled tasks
4 Features of performing background jobs in file and client-server versions
5 Creating metadata for a routine task
6 Job Console
7 Working with routine tasks
7.1 Job objects
7.2 Getting a list of tasks
7.3 Creation
7.4 Uninstallation
7.5 Getting a job object

Job mechanism

The job engine is designed to perform any application or functionality on a schedule or asynchronously.

The task mechanism solves the following tasks:

  • Ability to define regulatory procedures at the system configuration stage;
  • Execution of specified actions according to schedule;
  • Making a call to a given procedure or function asynchronously, i.e. without waiting for its completion;
  • Tracking the progress of a specific task and obtaining its completion status (a value indicating whether it was successful or not);
  • Obtaining a list of current tasks;
  • Ability to wait for one or more tasks to complete;
  • Job management (possibility of cancellation, blocking of execution, etc.).

The job mechanism consists of the following components:

  • Metadata of routine tasks;
  • Regular tasks;
  • Background jobs;
  • Task Scheduler.

Background jobs are designed to perform application tasks asynchronously. Background tasks are implemented using the built-in language.

Scheduled tasks - designed to perform applied tasks on a schedule. Routine tasks are stored in the information base and are created based on metadata defined in the configuration. Metadata of a regulatory task contains information such as name, method, use, etc.

A routine task has a schedule that determines at what times the method associated with the routine task must be executed. The schedule, as a rule, is specified in the information base, but can also be specified at the configuration stage (for example, for predefined routine tasks).

The task scheduler is used to schedule the execution of routine tasks. For each scheduled task, the scheduler periodically checks whether the current date and the time of the routine task schedule. If it matches, the scheduler assigns that task to execution. To do this, for this scheduled task, the scheduler creates a background task, which performs the actual processing.

Background jobs

Background jobs are convenient to use to perform complex calculations when the result of the calculation can take a long time to obtain. The job engine has the means to perform such calculations asynchronously.

Associated with a background job is a method that is called when the background job runs. Any procedure or function that is not global can act as a background job method. common module, which can be called on the server. Background job parameters can be any values ​​that are allowed to be passed to the server. The parameters of a background job must exactly match the parameters of the procedure or function that it calls. If the background job's method is a function, its return value is ignored.

A background job can have a key - any application value. The key introduces a restriction on the launch of background jobs - only one background job can be executed per unit of time with a specific key value and a given background job method name (the method name consists of the module name and the name of the procedure or function). The key allows you to group background jobs that have the same methods according to a specific application characteristic so that no more than one background job is executed within one group.

Background jobs are created and managed programmatically from any connection. Any user is allowed to create a background job. Moreover, it is executed on behalf of the user who created it. A user with administrative rights or the user who created these background jobs is allowed to receive tasks, as well as wait for their completion, from any connection.

A background job is a purely session object and does not belong to any user session. For each task, a special system session is created, running on behalf of the user who made the call. Background jobs do not have persistent state.

A background job can spawn other background jobs. In the client-server version, this allows you to parallelize complex calculations across cluster worker processes, which can significantly speed up the calculation process as a whole. Parallelization is implemented by spawning several child background jobs and waiting for each of them to complete in the main background job.

Background jobs that complete successfully or fail are stored for 24 hours and then deleted. If the number of completed background jobs exceeds 1000, the oldest background jobs are also deleted.

Scheduled tasks

Scheduled tasks are used when it is necessary to perform certain periodic or one-time actions according to a schedule.

Scheduled tasks are stored in the information base and are created based on the metadata of the routine task defined in the configuration. Metadata specifies such parameters of a routine task as: called method, name, key, possibility of use, sign of predetermination, etc. When creating a routine task, you can additionally specify the schedule (can be specified in the metadata), values ​​of the method parameters, name of the user on whose behalf the carry out routine tasks, etc.

The creation and management of scheduled tasks is performed programmatically from any connection and is permitted only to users with administrative rights.

Note. When working in the file version, it is possible to create and edit routine tasks without launching the task scheduler.

Associated with a routine task is a method that is called when the routine task is executed. The routine task method can be any procedure or function of a non-global common module that can be called on the server. The parameters of a routine task can be any values ​​that are allowed to be transmitted to the server. The parameters of a routine task must exactly match the parameters of the procedure or function that it calls. If the routine task method is a function, then its return value is ignored.

A routine task can have a key - any application value. The key introduces a restriction on the launch of scheduled tasks, because per unit of time, among routine tasks associated with the same metadata object, only one routine task with a specific key value can be executed. The key allows you to group routine tasks associated with the same metadata object according to a specific application characteristic so that no more than one routine task is performed within one group.

During configuration, you can define predefined routine tasks. Predefined routine tasks are no different from regular routine tasks, except that they cannot be explicitly created or deleted. If in the metadata of the scheduled task it is set sign of a predetermined routine task, then when updating the configuration in the infobase, a predefined routine task will be automatically created. If the predetermined flag is cleared, then when updating the configuration in the infobase, the predefined routine task will be automatically deleted. The initial values ​​of the properties of a predefined scheduled task (for example, a schedule) are set in the metadata. In the future, when the application is running, they can be changed. Predefined routine tasks have no parameters.

The routine task schedule determines at what time the routine task should be run. The schedule allows you to set: the date and time of the start and end of the task, the period of execution, the days of the week and months by which the scheduled task must be performed, etc. (see the description of the built-in language).

Examples of routine task schedules:

Every hour, just one day

RepeatDays Period = 0, RepeatDays Period = 3600

Every day once a day

RepeatDays Period = 1, RepeatDays Period = 0

One day, one time

PeriodRepeatDays = 0

Every other day once a day

PeriodRepeatDays = 2

Every hour from 01.00 to 07.00 every day

PeriodRepeatDays = 1
Repeat PeriodDuring Day = 3600
Start Time = 01.00
End Time = 07.00

Every Saturday and Sunday at 09.00

PeriodRepeatDays = 1
Days of the Week = 6, 7
Start Time = 09.00

Every day for one week, skip a week

PeriodRepeatDays = 1
PeriodWeeks = 2

At 01.00 once

Start Time = 01.00

Last day of every month at 9:00.

PeriodRepeatDays = 1
DayInMonth = -1
Start Time = 09.00

Fifth day of every month at 9:00

PeriodRepeatDays = 1
DayInMonth = 5
Start Time = 09.00

Second Wednesday of every month at 9:00

PeriodRepeatDays = 1
DayWeekInMonth = 2
Days of the Week = 3
Start Time = 09.00

You can check whether a task is running for a given date (the RequiredExecution method of the ScheduleTasks object). Scheduled tasks are always performed under the name of a specific user. If the user of the scheduled task is not specified, then execution occurs on behalf of the default user who has administrative rights.

Routine tasks are executed using background tasks. When the scheduler determines that a scheduled task should be launched, a background job is automatically created based on this scheduled task, which performs all further processing. If this routine task is already running, it will not be run again, regardless of its schedule.

Scheduled tasks can be restarted. This is especially true when the routine task method must be guaranteed to be executed. A routine task is restarted when it terminates abnormally, or when the worker process (in the client-server version) or the client process (in the file version) on which the routine task was executed is terminated abnormally. In the scheduled task, you can specify how many times it needs to be restarted, as well as the interval between restarts. When implementing the restartable routine task method, you must take into account that when restarted, its execution will start from the beginning, and not continue from the moment of abnormal termination.

It's important to remember that End time will not necessarily complete the background job at the specified time. Some statements:
* A background job can ignore its automatic cancellation if it is not stuck but continues to run for some reason
that not all platform operations can be reversed. If fulfilled cyclic code built-in language, then cancel the job
maybe otherwise no. It all depends on what the job does.
* End time - the boundary within which a task can start rather than end?
* Forced termination of a task rolls back the changes made to the start of the transaction?

Features of executing background jobs in file and client-server variants

The mechanisms for executing background jobs in the file and client-server versions are different.

  • In the file version, you need to create a dedicated client process that will perform background jobs. To do this, the client process must periodically call the global context function ExecuteJobProcessing. Only one client process per infobase should process background jobs (and, accordingly, call this function). If a client process has not been created to process background jobs, then when programmatically accessing the job engine, the error “Job Manager is not active” will be displayed. It is not recommended to use a client process that processes background jobs for other functions.

Once the client process processing background jobs is started, other client processes are able to programmatically access the background job engine, i.e. can run and manage background jobs.

In the client-server version, a task scheduler is used to execute background jobs, which is physically located in the cluster manager. For all queued background jobs, the scheduler gets the least loaded worker process and uses it to run the corresponding background job. The worker process executes the job and notifies the scheduler of the execution results.

In the client-server version, it is possible to block the execution of routine tasks. The execution of routine tasks is blocked in the following cases:

  • An explicit blocking of routine tasks has been installed on the information base. The lock can be set via the cluster console;
  • There is a connection block on the infobase. The lock can be set via the cluster console;
  • The SetExclusiveMode() method with the True parameter was called from the built-in language;
  • In some other cases (for example, when updating the database configuration).

Creating metadata for a routine task

Before you programmatically create a routine task in the infobase, you need to create a metadata object for it.

To create a metadata object for a routine task in the configuration tree in the “General” branch for the “Routine tasks” branch, execute the “Add” command and fill in the following properties of the routine task in the properties palette:

Method name - indicate the name of the routine task method.

Key - specify an arbitrary string value that will be used as the key of the scheduled task.

Schedule - indicates the schedule of the routine task. To create a schedule, click the “Open” link and in the schedule form that opens, set the required values.

On the “General” tab, the start and end dates of the task and the repeat mode are indicated.

On the “Daily” tab, the daily schedule of the task is indicated.

Specify the schedule:

  • start time and end time of the task;
  • task completion time, after which it will be forcibly terminated;
  • task repetition period;
  • duration of pause between repetitions;
  • execution duration.

It is allowed to specify an arbitrary combination of conditions.

On the “Weekly” tab, the weekly schedule of the task is indicated.

Select the checkboxes for the days of the week on which the task will be executed. If you want to repeat the task, specify the repeat interval in weeks. For example, the task is executed in 2 weeks, the repeat value is 2.

On the “Monthly” tab, the monthly schedule of the task is indicated.

Select the checkboxes for the months in which the task will be executed. If necessary, you can specify a specific day (month or week) of execution from the beginning of the month/week or the end.

Usage - if set, the task will be executed according to the schedule.

Predefined - if set, the task is a predefined task.

Number of retries in case of abnormal termination - indicates the number of retries in case of abnormal termination.

Retry interval on abnormal termination - specifies the retry interval upon abnormal termination. Examples

Creating a background job “Full-text search index update”:

BackgroundTasks.Run("UpdatingFullTextSearchIndex");

Creating a routine task “Recovery of sequences”:

Schedule = New ScheduleTask;
Schedule.PeriodRepeatDays = 1;
Schedule.RepeatPeriodDuringDay = 0;

Task = RoutineTasks.CreateRoutineTask("Restoring Sequences");
Job.Schedule = Schedule;
Task.Write();

Job Console

Processing with ITS, manages routine tasks: ConsoleTasks.epf

Working with routine tasks

Job Objects

Job objects are not referenced, but are stored in the database in some special storage.

If the "Predefined" flag is enabled in the metadata, then such an object is created automatically when 1C:Enterprise is launched and always exists in exactly one instance. Such an object cannot be deleted.

If the "Predefined" flag is not set, then objects of such a task are created and deleted programmatically, specifying the schedule and parameters.

Getting a list of tasks

The list of tasks can be obtained using the method Get RoutineTasks global job manager RoutineTasks

ScheduledJobsManager

Get ScheduledJobs (GetScheduledJobs)

Syntax:

Get RoutineTasks(<Отбор>)

Parameters:

<Отбор>(optional)

Type: Structure. Structure defining selection. Structure values ​​can be: UniqueIdentifier, Key, Metadata, Predefined, Usage, Name. If selection is not specified, all routine tasks are obtained.

If you are filtering by metadata, then as the Metadata value you can specify either the metadata object of the routine task or its name.

Return value:

Type: Array.

Description:

Receives an array of routine tasks for a given selection. Receiving scheduled tasks is only possible for the administrator.

Availability:

For Each Regular of the Regulatory Cycle
NewLine = List of ScheduledTasks.Add();
NewRow.Metadata = Regular.Metadata.View();
NewLine.Name = Regular.Name;
NewString.Key = Regular.Key;
NewLine.Schedule = Schedule.Schedule;
NewLine.User = Regular.UserName;
NewString.Predefined = Regular.Predefined;
NewString.Use = Regular.Use;
NewString.Identifier = Regular.UniqueIdentifier;

LastTask = Regular.LastTask;
If LastTask is Undefined Then
NewLine.Running = LastTask.Start;
NewRow.State = LastTask.State;
endIf;
EndCycle;

Creation

Created by the Create RoutineTask method for the manager of routine tasks:

RoutineTask = RoutineTasks.CreateRoutineTask(MetadataSelection);

RegularTask.Name = Name;
RegularTask.Key = Key;
RegularTask.Use = Usage;
RoutineTask.UserName = UsersSelection;
RoutineTask.Number ofRepetitionsAtEmergencyCompletion =NumberofRepetitionsAtEmergencyCompletion;
ScheduledTask.RepeatIntervalAtEmergencyCompletion = RetryIntervalAtEmergencyCompletion;
ScheduleTask.Schedule = Schedule;
RegularTask.Record();

TaskObject = RoutineTasks.CreateRoutineTask("ExchangeExchange");

TaskObject.Name = Name;
JobObject.Use = True;

The task object has a "Parameters" field in which the method parameters are specified:

ScheduledJob

Parameters

Usage:

Read and write.

Description:

Type: Array. An array of parameters for a scheduled task. The number and composition of parameters must correspond to the parameters of the routine task method.

Availability:

Server, thick client, outer join.

Note:

Read and write capabilities are only available to the administrator.

Removal

Deleted using the Delete() method of the task object:

ScheduledTask.Delete();

Getting a Job Object

  • list via the GetRoutineTasks method:
    Routine = RoutineTasks.GetRoutineTasks(Selection);
  • via the FindByUniqueIdentifier of the task manager method:
    Task = ScheduledTasks.FindByUniqueIdentifier(UID);

[you must register to view the link]

Allows us to perform any calculations in the system unnoticed by the user, that is, in the background. Moreover this mechanism allows us to parallelize the calculation process. We can even parallelize the procedure that will be executed. To do this, our background job must run several more background jobs. In this case, the processes are parallelized and, if we have a multiprocessor, multi-core system, our algorithm will work efficiently. After launching several processes, we can tell the system that it needs to wait for the completion of these processes in order to somehow combine the result.

For example, in typical configurations, while the user is working, various kinds of background service jobs are running. This can be evidenced by log entries that record the fact that such actions were performed. Moreover, this does not affect the user’s work in any way, he simply does not notice them.

Ideally, a background job is implemented in a client-server version, in which case the entire load goes to the server. As for the file option, a background job is possible, but it has some peculiarities.

This is what the system will produce if you do not take these features into account and run a background job in the file version information base.


The 1C background job has some limitations. Since it is executed on the server side, there is no possibility of interactive work with the user. For example, you cannot display a message, or any information at all. All this data needs to be stored within the information base and further processed in some way.
By contacting the syntax assistant, you can get more detailed information about 1C background jobs. It should be noted here that this object is purely software and is not stored in the database in any way. That is, we create an instance of the class, initialize the properties and launch it for execution.

What tools do we have to manage background jobs? This facility is a metadata object "BackgroundTask Manager". This object has a method "Run", using this method, the background job is launched.

It has the following parameters:
"MethodName"- the name of the procedure or function to be executed, and it must be a procedure or function of the server context;

"Options"- an array of parameters, the number of elements of which must correspond to the number of parameters of our procedure/function specified in the parameter "MethodName";

"Key"- a certain uniqueness key, which is a line by which the system understands whether a background task needs to be launched or whether such a task is already running;

"Name"- here you can specify an arbitrary description of our method.

The return value is an object "BackgroundTask", containing the current method name, the current key, and several more properties and methods. One such method is the method "WaitComplete". Its purpose is that we can tell the system not to do anything until the background job is completed.

Background job 1C 8.2, 8.3 - Example of use

Let's give an example of working with 1C background jobs. First, we will create a simple algorithm that will briefly load the 1C system in such a way that we cannot do anything at this time.

To do this:

1. Let's create a common module "BackgroundTask Handlers", which will be compiled on the server side;


2. We will describe the export procedure in it "ProduceBackgroundCalculation(Parameter)", which takes one parameter of string type;

Procedure PerformBackgroundCalculation(Parameter) ExportStartTime = CurrentDate() ; While CurrentDate() - Start Time< = 6 Цикл КонецЦикла ; КонецПроцедуры Процедура КнНажатие() ОбработчикиФоновыхЗаданий. ПроизветиФоновоеВычисление("Some parameter") ; End of Procedure
Ready. Now, when you start processing and press a button, the system freezes for several seconds, during which nothing can be done. This is exactly what we needed to do.

Now we will ensure that these calculations are carried out in the background, that is, so that the background task 1C 8.2, 8.3 is executed, but does not interfere with us.

To do this:

1. In processing, in the button click event, write the following code.

Procedure KnPress() Parameters = New Array; Options. Add( "Some parameter") ; BackgroundTask. Run ( "BackgroundTask Handlers. Perform BackgroundComputation", Parameters, New UniqueIdentifier, "Test task") ; End of Procedure

Here we pass the name of the common module procedure as the first parameter, and an array of parameters as the second. The third parameter must be passed unique key and fourth, some description of our procedure.

Often, when maintaining records, there is a need to periodically perform certain actions without user intervention. Routine and background tasks in 1C are those mechanisms that are provided for this purpose in the eighth version of the program and allow:

  • Set up timely delivery of documents;
  • Calculate balances and totals;
  • Ensure frequency of mailing;
  • Check and delete irrelevant data.

Background and scheduled task - what is it and where is it configured?

A routine task is a mechanism built into 1C that allows you to configure and, in accordance with the established schedule and frequency, perform a certain sequence of actions.

A background job is an action generated by a routine operation and does not require direct user participation.

A routine task is created in the configurator mode:

  • In the configuration tree window we find the corresponding branch (Fig. 1);
  • Click the add button;
  • In the window that opens, you must specify a name that allows you to identify the object in the configuration;

Fig.2

  • Opposite the inscription “Schedule” (Fig. 2) there is an inscription “Open”, clicking on which opens a window for setting the time and frequency of execution of the handler (Fig. 3);

Fig.3

  • It is also necessary to fill in the “Method name” (the name of the procedure called from the general module and describing the behavior algorithm of the program will be entered here);
  • The “Name” and “Key” fields allow you to group objects;
  • The checked “Use” checkbox indicates the activity of the scheduled operation;
  • “Predefined” should be set if the handler should be launched immediately after it is added to the database, otherwise the launch can be done from the corresponding processing (more about it below);
  • The “Number of retries” and “Retry interval” parameters describe the program’s behavior if an exception occurs while executing a background job.

So, using the mechanism of routine operations, you can set the schedule and main actions of background jobs. Let's now look at their features.

Features of background jobs

The main feature of this mechanism is that the background process runs asynchronously.

What does this mean? The fact is that with a synchronous work model, if any algorithm is executed, the user interface is blocked. In our case, the user can continue to enter and edit data even if the procedure is running. The asynchronous programming model involves separation of computational threads.

Thus, background jobs in 1C can spawn their own processes, distributing calculations across various servers included in the same cluster.

Features of working in client-server mode

  • Execution planning and control is carried out by a scheduler from a server cluster;
  • If a request for execution appears, the scheduler looks for cluster worker processes with minimal load and distributes tasks to them for execution;
  • Each process can perform several parallel computing;
  • After a task arrives, the process connects to the database and executes the algorithm in it;
  • The process reports the results to the scheduler.

Background jobs in file mode

Before platform version 8.3.3.641, working with background jobs in the file version presented some difficulties:

  1. It was necessary to launch a separate session that would work around the clock, replacing the scheduler;
  2. This session should have periodically executed the RunJobProcessing() method.

After the update, each start of the thick and thin clients, if the AllowExecuteScheduledJobs key is specified in the launch settings (Fig. 4) in the “Additional” field, initiates an additional thread for connecting to the database, which does not affect the user’s work in any way, but only performs background tasks. operations.

Fig.4

It should be taken into account that even in the file version of work, background processes do not allow interactive work with the user (service messages, warnings, and questions will not be displayed). That is, they must be coded as if they would be executed on the server side.

How to disable scheduled tasks

Unused tasks can be disabled by simply unchecking the “Use” checkbox in the object properties.

In the case when the administrator needs to prohibit the use of routine and background operations for the entire database as a whole (for example, several databases are stored on the server, of which only one is the main one, and the rest are used only for development), it is necessary to use the database administration utility. You can also check the “Set blocking of routine tasks” checkbox in the database created on the server.

In addition, the ITS disks have a special processing “Task Console”, which allows you to edit the schedule of background processes and change their activity.

Asynchronous programming concept

The asynchronous programming concept is that the result of a function is not immediately available, but after some time in the form of some asynchronous (violating the normal order of execution) call.

Those. The main idea of ​​asynchronous programming is to issue individual method calls and continue doing other work in parallel without waiting for the calls to finish.

Some methods that minimize the likelihood of exceptions do not require an asynchronous approach, but others require it at the very beginning of development.

As can be seen from the graphs, there is no coefficient of useful interactive user actions with a synchronous programming model, since the system blocks user interface, while with the asynchronous model, the user continues to actively work in the system.

When running synchronously, the application has only one thread. With the asynchronous programming model, you can run multiple threads in parallel and react to new user actions as they run. Once the n-thread is executed, you display the result on the screen.

Background tasks in 1C:Enterprise 8

In 1C:Enterprise 8, background jobs are designed to perform application tasks asynchronously. They can generate child background jobs, for example, to parallelize complex calculations across different working servers of the cluster in a client-server mode of operation.

It is possible to limit the execution of background jobs that have the same methods based on a specific application criterion. Software creation and management of background jobs is possible from any user connection to the system information base. The background job runs on behalf of the user who created it.

The task mechanism functions in both the client-server and file modes of operation, but the capabilities for administering and executing tasks in both versions are somewhat different.

Client-server option

In the client-server version, task scheduling is carried out by the task scheduler, which is physically located in the cluster manager.

The scheduler periodically checks to see if any requests have been received to run background jobs. If there are jobs that need to be executed, the scheduler determines the least loaded worker processes in the cluster and sequentially assigns each of them its own job to execute. Thus, the same worker process can potentially execute multiple jobs in parallel. After a job is received by a worker process, the worker process establishes a connection to the infobase and executes the job within that connection. After the job completes, the worker process notifies the scheduler whether the job completed successfully or unsuccessfully.

File option

Starting with version 8.3.3.641 of the platform, the developers have significantly simplified the work with background jobs in the file version.

Previously, to automatically execute tasks, it was necessary to launch a separate, additional 1C:Enterprise session, used as a task scheduler. And in this session it was necessary to periodically execute the built-in language method ExecuteTaskProcessing(). This approach was quite cumbersome, inconvenient and greatly limited the use of background and routine tasks in the file version of work.

Now everything has become much easier. If a thin or thick client starts, and also if the web server has client connections, then in each of these applications another thread is automatically launched with a connection to the database. These threads are engaged in performing background and routine tasks.

Each of the listed applications runs its own background tasks. If an application has initiated several background jobs, they are executed sequentially, in the order they were received.

The obvious disadvantage of 1C background jobs: since they are executed on the server side, there is no possibility of interactive work with the user (for example, it is impossible to display a message or some other information; all this data must be stored within the information base and further processed in some way).

It should be noted that background jobs are purely software objects and cannot be stored in the database. That is, we can only create an instance of the class, initialize its properties and launch it for execution.

An example of asynchronous code execution in 1C:Enterprise 8

“Writing programs in which the result of a function call arrives unknown when is much more difficult than ordinary ones. Nested calls, error handling, control over what is happening - everything becomes more complicated,” only those who do not know how to properly use the platform’s capabilities will say this, but not us!

Let's demonstrate all the simplicity and elegance of asynchronous code execution in 1C:Enterprise 8!

Step 1. Let's create a new information security system for configuration development

Step 2. In the configuration we will add the general module “Asynchronous Handlers”

Why did we add a shared module? Everything is simple here: to perform asynchronous operations in 1C:Enterprise 8, background jobs are used, which have their own manager - “BackgroundTask Manager”. This object has a “Run” method, with the help of which the background task is launched.

Let's turn to the syntax assistant.

So we will need a common module.

Step 3. In the general module “Asyncronous Handlers” we will add the export procedure OurLongOperation()

Procedure OurLongOperation(Duration) Export // Simulation of a long-term action (Duration sec.). OperationStartDate = CurrentDate(); While CurrentDate() - Operation Start Date< Длительность Цикл КонецЦикла; КонецПроцедуры

Step 4. Add “Asynchronous Programming Concept” processing to the configuration (you can create external processing)

Add one attribute to the form:

Duration (Number)

and two teams

Perform LongOperation;

Perform a Long-Long Operation Asynchronously.

Step 5. According to the syntax assistant, fill out the form module

&On the Client Procedure Perform Long-RunningOperation(Command) ExecuteLong-RunningOperationOnServer(); EndProcedure &OnServer Procedure ExecuteLongOperationOnServer() AsynchronousHandlers.OurLongOperation(Duration); End of Procedure &On the Client Procedure Perform Long-running Operation Asynchronously (Command) Perform Long-running Operation Asynchronously on Server (); End of Procedure &On the Server Procedure Perform Long-running Operation Asynchronously On the Server() Parameters = New Array; Parameters.Add(Duration); BackgroundTasks.Execute("AsynchronousHandlers.OurLongOperation", Parameters, New UniqueIdentifier, "Example of asynchronous programming concept"); End of Procedure

Step 6. Let's launch and check!

Result:

If we click on the “Perform long operation” button, then the user interface is blocked for “Duration” seconds;

If we click on the button “Perform long-running operation asynchronously”, then the user interface is not blocked, but program code runs in parallel.

We can verify that the program code is executed asynchronously by looking at the log.

We can debug program code that runs in the “background” if we set the appropriate property in the debugging parameters.

An example of asynchronous code execution in 1C:Enterprise 8 using BSP

Let's consider an example of the implementation of the asynchronous programming concept in 1C:Enterprise 8 in the BSP using the example of processing “Current Affairs”.

The logic is as follows: when the program is launched, the work area of ​​the start page is initialized, where the “Current Affairs” processing form can be displayed. This form is filled out by the user's current affairs, and it takes time to fill it out. If developers did not have the ability to execute code asynchronously, then the user interface would be blocked while the processing form was being filled out!

Let's analyze the program code of the form.

The form event “When CreatedOnServer” calls the “RunBackgroundTask” procedure - this is what we need.

Without being distracted by the nuances, let’s analyze this procedure

And here we see that the background job manager and its “Run” method are used. Note that developers store a unique ID for the background job.

To do this, developers use the method ConnectWaitHandler(<ИмяПроцедуры>, <Интервал>, <Однократно>).



In a connected procedure Connectable_CheckTaskComplete() developers call the function JobCompleted(TaskID)


This function checks the execution of a background job by identifier.

It should be noted that the BSP has developed general modules to support long-term server operations.

Thus, the asynchronous programming concept in 1C:Enterprise 8 slightly increases the complexity of solving problems for the developer, but significantly improves the functionality of the program from the user’s point of view.

Probably every 1C 8.3 programmer sooner or later had to set up the execution of certain tasks on a schedule. Below I will give detailed description of these mechanisms, I hope it will be useful information for beginner 1C programmers. This is very convenient, because it does not require human action, the routine task is configured once and works according to your schedule.

You will find detailed instructions using an example below.

What are routine and background tasks in 1C

  • Scheduled tasks is a special 1C Enterprise 8.3 mechanism designed to perform a specific action according to a given schedule.
  • Background job- objects generated by a routine task that directly perform the intended action without the participation of the user or 1C 8.2 programmer.

The mechanism of scheduled and background jobs works in client-server mode work (SQL), thanks to the functionality of the DBMS. If you have a file database, then the task can also be configured, but according to a slightly different principle.

Setting up background jobs in 1C client-server mode

First, let's create a new metadata object - a routine task. I will call my task “Loading Currency Rates”. Let's look at the properties palette of this configuration object:

Get 267 video lessons on 1C for free:

  • Method name— path to the procedure that will be executed in a background job according to a given schedule. The procedure must be in a common module. It is recommended not to use standard ones, but to create your own. Don't forget that background jobs run on the server!
  • Usage— a sign of using a routine task.
  • Predetermined— indicates whether the routine task is predetermined. If you want the routine task to work immediately after being placed in the database, specify this flag. Otherwise, you will need to use Job Console processing or cause the job to run programmatically.
  • Number of retries when a task terminates abnormally— how many times the background job was restarted if it was executed with an error.
  • Retry interval when job terminates abnormally— how often the background job will be restarted if it was completed with an error.

And the most interesting setting is Schedule:

Here you configure the launch interval of the procedure specified in the “Method name” field. Let's say I configured

Attention! Don't forget to disable the blocking of routine and background tasks at the DBMS level!

This can be done in the administration utility of the client-server version or when creating a new database:

Setting up routine tasks in 1C file mode

IN file mode Setting up such jobs is somewhat more difficult. For such a task, a separate session of the 1C program must be launched. This is often solved by creating a “technical” user whose session is always running.

In file mode, a routine job is initialized when the “RunTaskProcessing()” method is launched.

For a specific user, you can configure this method to run using another method −

ConnectWaitHandler( <ИмяПроцедуры>, <Интервал>, <Однократно>).

  • Procedure name— the name of the procedure connected as a wait handler. Name of the exported module procedure managed application(regular application module) or global common module. The procedure must be located on the client.
  • Interval— period between executions of operations in seconds.
  • One time- how to complete the task, once or not.

ConnectWaitHandler, 3600 ) ;

A two-minute video that shows how to set up a routine task in the 1C configurator:

Reviews