Universal regulatory task. Scheduled and background jobs Error executing the background job for checking the unloading

Question: The background job process crashed...


Good afternoon everyone and have a good week!)
Enterprise accounting, edition 3.0 (3.0.46.11).
Platform 8.3.9.2033.
When posting documents in groups, the error “The background job process has terminated abnormally” occurs. No reasons are given...
Rebooting the SQL server, 1C server (you never know) doesn’t help... Maybe someone has encountered a similar problem??? It’s even difficult to say when this error appeared because we haven’t used group execution (closing the month) for a long time...

Answer:() () Good afternoon again) I turned on the technology magazine and found these interesting things (maybe you know what the problem is?):
An attempt was made to perform an operation on an object that is not a socket...
The process ends. Outgoing call denied...
No servers were found hosting the service...

Question: Background jobs


Platform 1C:Enterprise 8.3 (8.3.9.2170), conf BP 3.0.
The configuration configures integration through external data sources (DBMS type - OracleDatabase). A number of tables have been added from which master data and transactions are loaded. Because There was a lot of data, so it was decided to do a batch download through background jobs. The portion size is 100,000, the batch size is 10,000, the number of transactions in the document is 1000, the number of simultaneously running background jobs is 8.
I launch, load, everything is ok. But if I put it on at night, it feels like 1c goes into sleep mode, i.e. after some time, as the log shows, background jobs are started, but not completed. As a result, it turned out that the tasks started at 12 at night, and were completed at 8 in the morning (when I moved the mouse) and after that they continued to be executed in normal mode. I ran it in both thin and thick clients. There is a setting in the parameters - the time to fall asleep in a passive session is 1200, but does this not only apply to the thin client and could this be a problem? I don’t want to disable this, because... users do not exit the program, let them fall asleep. Has anyone encountered a similar problem? How did you decide?

Answer:

There is no such possibility.

What's the point of running a background job and waiting for it to complete?
so as not to create more than 8 background tasks?

Drag the "manager" of background jobs to the server side and let it control....

I ran 40-50 background tasks on the Pentuim D840 - the flight was normal, then it was limited by the processor/memory.

Question: How to transfer a file to a background job


Platform 8.3.6.2152
You need to transfer the file from UV to a background job for subsequent processing.
Did this:
&OnClient
Procedure Command1(Command) FileDD = New BinaryData(FileName); StorageAddressForBackground = PlaceInTemporaryStorage(FileDD, UniqueIdentifier); Start UploadLoadOnServer(StorageAddressForBackground) EndProcedure &OnServer Function StartUploadLoadOnServer(StorageAddressForBackground) Method Parameters = New Array; MethodParameters.Add(StorageAddressForBackground); Job = BackgroundTasks.Run("MyGeneralModule.MyBackground", MethodParameters); EndFunction
In the general module:

Procedure MyBackground(StorageAddress) Export FileDD = GetFromTemporaryStorage(StorageAddress); If TypeValue(FileDD) = Type("BinaryData") Then Journal EntryRegistration Journal EntryRegistration("Debug","No DD"); EndIf ; End of Procedure I tried this: PlacedFiles = New Array; PlacedFiles.Add(NewDescriptionofTransferFile(FileName)); PlacedFiles = New Array; If NOT PlaceFiles(PlaceFiles, PlaceFiles, False, UniqueIdentifier) ​​Then Return ; EndIf ; StorageAddressForBackground = PlacedFiles.Storage; I tried this: StorageAddressForBackground = PlaceInTemporaryStorage(Undefined, UniqueIdentifier); PlaceFile(StorageAddressForBackground, FileName, False);
It is transferred normally from the background to the client via temporary storage, but for some reason it does not transfer from the client to the background.

Answer: In general, everything turned out to be quite simple. It turns out that you can stupidly pass Binary Data as a parameter to a background job. For unskilled amateurs to quote references and tell them that “this is how it was intended”, the working code is:
&OnClient
Procedure Command1 (Command) Start UploadLoadOnServer(New BinaryData(FileName)) EndProcedure
&OnServer Function StartUploadLoadOnServer(DD)Method Parameters = New Array; MethodParameters.Add(DD); Job = BackgroundTasks.Run("MyGeneralModule.MyBackground", MethodParameters); EndFunctions Procedure MyBackground(FileDD) Export If TypeValue(FileDD) = Type("BinaryData") Then Journal EntryRegistration("Debugging","Yes DD"); Otherwise Journal EntryRegistration("Debug","No DD"); EndIf ; EndProcedure

Question: Running a background job under the desired user


Hello!
There is 1C:Enterprise 8.3 (8.3.11.2924), UT 11.3.4.93 client - server.
In this configuration, movements in the "Settlements with clients on documents" register are performed not at the time of document posting, but with the routine task "Execution of deferred movements in settlements with clients\suppliers".
At the same time, sometimes the routine task generated an error, because tried to make movements in a closed period (Before the editing ban date). In the settings of the routine task, we registered a special user whose ban date was open, after which everything began to work.
However, there is a need to ensure that these movements in the registers are done at the time the document is posted, and not when the background job is started according to the schedule.
If you run the code itself, which performs a routine task when posting a document, then the same error occurs - the period is closed. And if you programmatically run a background task that runs the same code at the time the document is posted, then it causes exactly the same error, because the period is closed, and the background job, launched programmatically, is launched under the name of the current user, and his ban date is closed. However, when a background job is launched according to a schedule, which has the “correct” user installed in the scheduler, then everything goes with a bang. Here's how to do this programmatically, how to programmatically run a background task under the desired user "through the scheduler" as standard scheduled tasks do, please tell me?

Answer:

Isn't it the one it's configured for?
This must be a configuration glitch

Lis2007 said:

Hello! Sometimes the routine task generated an error because... tried to make movements in a closed period (Before the editing ban date). In the settings of the routine task, we registered a special user whose ban date was open, after that everything started working

Click to expand...

Question: Debugging a background job


The background job is running with an error. I decided to debug it.
I launch it through external processing with one line:
BackgroundTasks.Run("MyModule.MyTask");
It doesn't hit the breakpoint in the module.
Debugging on the server is allowed, debugging is checked, automatic connection, background jobs are enabled. What else could be the problem?

Answer: In common modules, there was a call to functions that required client rather than server execution. I had to put them in brackets #If Client Then. The background one also worked.

Question: Error during exchange


Good afternoon. Tell me where to dig:
I perform an exchange in the accounting database. About three dozen documents are uploaded from UT-shka through a standard exchange. They think for a long time (about an hour) and end with the message:
The background job process crashed

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 the user interface, while with an 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 restrict the execution of background jobs that have the same methods based on a specific application criterion. Programmatic 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 task 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 performs 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 a 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 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"); EndProcedure

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 “Perform long-running operation asynchronously” button, then the user interface is not blocked and the program code is executed 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 for the entire time the processing form was 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.

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 executed. 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 of the infobase.


The 1C background job has some limitations. Since it runs 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 it 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.

For 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") ; EndProcedure
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.

For 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") ; EndProcedure

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 needs to be passed a unique key and the fourth parameter some description of our procedure.

The problem is not new and is discussed from time to time on various 1C forums. The simplest and most popular solution is to reboot the 1C server. Unfortunately, this option is not always acceptable or highly undesirable. In such a case, there are more delicate solutions.

Here one of these methods in the form of brief step-by-step instructions:

1. Using the 1C server administration console, we are looking for problematic fa new job in the connection list (for example, by the start time of its operation, compared with the start time of a regulated job in the job console). We definethe worker process in which the hung connection is located.

2. Open the properties of this process and mark it as unused (if only one process is used, then you must first create a new worker process so that all active connections reconnect to it). We remember the PID number of this process.


3. We wait until all current connections move from the disabled process to one of the used ones. Ultimately, only problematic connections should remain in our process, which we want to remove.

4. On a computer with a 1C server, using the task manager, look for the corresponding rphost.exe process by the PID of the disabled worker process and delete it.

5 . Just in case, you can delete the 1C workflow that we disabled using admin. console and, if necessary, create a new one.

6. Ready. You can log into the job console and check the functionality of the scheduled job.

Background jobs in 1C can be launched automatically according to a schedule (i.e., they are instances of routine jobs), or the developer himself can initiate the launch of a background job to execute an arbitrary algorithm (a striking example is the generation of reports in the background).
IMPORTANT!!! For file databases, starting from platform version 8.3.3.641, it is not necessary to launch a separate session in which background jobs will be executed. Those. Previously, in file databases, to run background jobs, it was necessary to execute the global context method “RunTaskProcessing()”. Details at this link.

Procedure for running an arbitrary algorithm in a background job

To run our algorithm in a separate background job, we will use the method "Run()" background job manager: Syntax: Execute(<ИмяМетода>, <Параметры>, <Ключ>, <Наименование>)
  • <ИмяМетода>(required); Type: String
    The name of the exported procedure or function of a non-global common module that can be executed on the server, in the form ModuleName.MethodName.
  • <Параметры>(optional); Type: Array
    An array of parameters passed to the method. The number and types of parameters must match the method parameters. (more details in the Syntax Assistant)
  • <Ключ>(optional); Type: String
    If a key is specified, it must be unique among the keys of active background jobs that have the same method name as the background job.
  • <Наименование>(optional); Type: String.
    Task description.

Procedure for running a background job

In our case, we will use the export procedure located in the general module "GeneralModuleServer"(I think it is unnecessary to explain that the module must be server-side) Procedure Write Information ABOUT Products in the Background (BackgroundTask Parameter) Export Data Request = New Request ("SELECT | Products. Link AS Nomenclature | FROM | Directory. Nomenclature AS Products"); Fetch = DataRequest.Execute().Select(); While Selection.Next() MH Cycle = Information Registers.Product Data.CreateRecordManager(); MZ.Period = CurrentDate(); MZ.Nomenclature = Sampling.Nomenclature; MH.Information = BackgroundTaskParameter; MZ.Write(); EndCycle; End of Procedure In order to demonstrate the operation of the background job, we will create entries in our information register for each item, and the parameter will be passed from the form in which the background job is launched.

Background job start command

The parameter that we will pass to the execution procedure will be taken from the attribute of the managed form (attribute with the “String” type):

The managed form module code will look like this: &On the Client Procedure StartBackgroundJob(Command) StartBackgroundJobOnServer(); End of Procedure &On the Server Procedure Start Background Job On Server () // Form an array with parameters Job Parameters = New Array; JobParameters.Add(TaskParameter); // We start the background execution of the BackgroundTasks.Execute algorithm(// Our export method in the general module "GeneralModuleServer.WriteInformationOnProductsInBackground", // We pass an array with parametersTaskParameters, // Specify the task key New UniqueIdentifier, // Specify the name of the background job "Our background job "); EndProcedure

Execution result

As a result of executing the background job, entries will be generated in the information register (which is what we needed).