Вы все еще не знаете, как лучше организовать передачу файлов по сети на компьютеры под управлением Windows? Тогда вам сюда!
Background Intelligent Transfer Service (BITS) – служба ОС Windows, которая может передавать файлы в фоновом режиме. Она используется, в основном, для Windows Update.
Какой же интерес BITS представляет для разработчиков?
1. Возможность закачки файлов в фоновом режиме, незаметно для пользователя
2. Высокий уровень отказоустойчивости. Если сетевой кабель перерубят, или комп выпадет в «синий экран», то BITS докачает файлы, как только это станет возможно.
3. Intelligent сказано не зря. Если пользователь в данный момент ничего не качает и комп простаивает, BITS воспользуется освободившимися ресурсами. Эту фичу можно использовать, назначая различные приоритеты закачек.
Работать с BITS можно через специальный API
В своем проекте я использовал удобную, вполне рабочую «обертку» для .NET. Так же существует еще одна.
Ключевым объектом BITS является Job (не надо дословного перевода, назовем это «закачкой»).
Жизненный цикл «закачки» следующий:
1. Создание Job. Указываем название, описание, тип (Upload\Download) и приоритет
2. Добавление файлов. Job может содержать несколько файлов, если выбран тип Download.
3. Подписываемся на события закачки, если необходимо отслеживать прогресс в реальном времени.
4. Запуск закачки. Далее BITS все делает сам.
Важной особенностью BITS является то, что создать закачку может только пользователь, совершивший вход в систему, либо системная учетная запись. Тем, кто собирается использовать BITS, советую не забывать об этом.
Я сознательно не привожу примеров кода, они есть здесь и здесь.
Для дополнительного ознакомления есть замечательная статья на английском.
Background Intelligent Transfer Service (сокращенно BITS) — интеллектуальная служба операционной системы Windows, предназначенная для пересылки данных в фоновом режиме.
Служба BITS использует для фоновой передачи данных незагруженную часть трафика сети. В этом режиме Windows Update, остальные службы безопасности Windows, а также другие разрешенные приложения скачивают свои обновления и передают необходимую информацию.
Принцип работы протокола BITS
Для пересылки данных протокол BITS, на основании запроса соответствующего приложения, создает задание, которое активируется и помещается в очередь. Служба BITS может выполнять загрузку необходимых файлов с сервера или производить запись файлов на сервер с извещением о статусе пересылки.
Для передачи файлов может использоваться как фоновый, так и обычный режим. Для передачи в фоновом режиме протокол задействует свободную полосу пропускной способности сети. Если нагрузка на сеть увеличивается за счет использования ее другими приложениями, BITS снижает скорость фоновой передачи данных.
Протокол BITS оперирует тремя уровнями приоритетов для фоновой пересылки и только одним для обычной. Согласно механизма работы службы BITS выполнение заданий с низким приоритетом приостанавливается, пока не обработаются задания с высоким приоритетом. Если несколько заданий имеют один уровень приоритета, они разделяют доступный трафик. Передача особо крупных файлов может приостанавливаться или перемещаться в конец при наличии большой очереди заданий.
Использование протокола BITS в приложениях Windows
Для пересылки данных приложения системы используют следующие СОМ-интерфейсы протокола:
- IBackgroundCopyCallback — уведомляет об окончании передачи, изменении задания;
- IBackgroundCopyError — уведомляет об ошибках;
- IBackgroundCopyFile — уведомляет о файле (данных) в задании на пересылку;
- IBackgroundCopyJob — добавляет файлы в задание, назначает приоритеты, определяет статус задания, выполняет запуск и приостановку загрузки;
- IBackgroundCopyManager — формирует задания на загрузку файлов, информирует о текущих заданиях;
- IEnumBackgroundCopyFiles — уведомляет о количестве файлов в задании;
- IEnumBackgroundCopyJobs — информирует о списке заданий в очереди.
Сервис BITS регулирует механизм пересылки файлов любых размеров, очередность их загрузки, сохраняя запрос на выполнение задачи даже при отключении или перезагрузке системы до полного завершения передачи файла. То есть, при выходе из системы передача файлов приостанавливается, а при входе снова возобновляется. По окончании загрузки приложение, отправлявшее запрос на пересылку данных, информируется о получении файла.
Background Intelligent Transfer Service (BITS) is a system component in Microsoft Windows operating system that facilitates asynchronous, prioritized, and throttled transfer of files between machines using idle network bandwidth. It also plays a role in the download of files from a peer. This BITS Service is essential for Windows Updates to work properly. If the service is disabled, then any applications that depend on BITS, such as Windows Update or MSN Explorer, will be unable to automatically download programs and other information.
Background Intelligent Transfer Service BITS was first introduced on Windows 2000 which allows the transfer of files between server and client. Recent versions of Microsoft Update, Windows Update, Microsoft Systems Management Server and Windows Server Update Services use Background Intelligent Transfer Service to deliver application updates to clients.
Contents
- 1 How BITS service works
- 2 Background Intelligent Transfer Service (BITS) Version History
- 3 Determining the Version of BITS on a Computer
- 3.1 How To Start / Restart BITS service?
- 3.2 How To Stop BITS Service?
- 3.3 Start / Stop BITS using the Command prompt
How BITS service works
There are three types of transfer jobs performed by the Background Intelligent Transfer Service (BITS). A download job downloads files to the client, an upload job uploads a file to the server, and an upload-reply job uploads a file to the server and receives a reply file from the server application.
- Asynchronously transfer files in the foreground or background.
- Preserve the responsiveness of other network applications.
- Automatically resume file transfers after the network disconnects and computer restarts.
Background Intelligent Transfer Service (BITS) Version History
Microsoft first Introduced Background Intelligent Transfer Service on Windows 2000
Next Microsoft Upgraded BITS version 1.0 in Windows XP in 2001.
Then Version 1.2 arrived in mid-2002 to add the Automatic Updates service to Windows 2000.
With Windows Server 2003 Microsoft updates BITS Version 1.5 in late 2003 and brought command-line support, more upload features, and security improvements.
BITS version 2.0, released in mid-2004 as an update for multiple OS deployments, added more download features, bandwidth throttling and support for Server Message Block (SMB).
Released in mid-2007, BITS version 2.5 added support for IPv6 and custom HTTP headers, and better HTTP security.
With Windows Vista and Windows Server 2008, Microsoft included BITS version 3.0 with peer caching, notifications, temporary file access, HTTP redirect handling, additional Group Policy controls, and event logging.
In mid-2009 Microsoft Included BITS version 4.0 with Windows 7 and Windows Server 2008 R2, brought token-based security, standalone file server features, refined bandwidth throttling, and revised peer caching.
BITS 5.0, included with Windows 10 in mid-2016, added improvements to background copy jobs and support for older background copy jobs, and the ability to use BITS through APIs and PowerShell cmd lets.
With Windows 10 creator update Version 1703 Microsoft upgrade BITS version 10.1 with refined download and notification features.
Determining the Version of BITS on a Computer
To determine the version of BITS on the client computer, check the version of QMgr.dll. To find the version number of the DLL:
- Locate QMgr.dll in %windir%\System32.
- Right-click QMgr.dll and click Properties.
- Click the Version tab.
- Note the version number.
You can also use the following PowerShell code to determine the version of the .dll on your system:
get-item "C:\Windows\System32\qmgr.dll" | Select-Object -ExpandProperty VersionInfo
If the DLL also exists in %windir%\System32\Bits, repeat the previous steps. BITS uses the DLL with the higher version number.
How To Start / Restart BITS service?
On Windows computers, Background Intelligent Transfer Service is set to start automatically at startup. But due to some reason, if Service is not started, you may face different problems while check and installing windows updates. That causes you need to manually check and start the BITS service.
- To do this Press Windows + R key, type services.msc and hit the enter key to open Windows services.
- Now scroll down look for Background Intelligent Transfer Service.
- If this service is Running simply Right click on it and select Restart.
- This will Restart the BITS service and fix if the service is stuck due to any reason.
- Or if the Service is not started then simply double-click on it.
On the new popup under the general tab change the startup type to Automatic and start the service next to service status as shown below image.
How To Stop BITS Service?
If due to some reason BITS service get stuck not respond you may face High System Resource usage problem. Such as 100% CPU usage, High Disk or memory usage etc. And While troubleshooting these problems we need to Stop the BITs service to fix the issue. Also, Most of the users suggest on Microsoft Forum, and Reddit to Disable the BITS service to fix the High CPU usage problem.
To Disable the BITS service
- Again open windows services by press windows + R, type services.msc and hit the enter key.
- Double-click on BITS service, Change the startup type to disable and Stop the service if its running
Start / Stop BITS using the Command prompt
Also, you can use the windows command prompt to Start / Stop the BITS service. To do this open the Command prompt as administrator.
- Then first use command sc bits query to Check The service is running or not.
- If everything is OK, You will see “STATE: 2 RUNNING” in the outputs.
- You may find “SATE: 1 STOP_PENDING“.
Then you can use the command net start bits to Start the BITs service. And You can use the command net stop bits to Stop the service.
I hope this post helps you to know about Background Intelligent Transfer Service. How BITS service works on the windows computer, Different versions of BITs service with Feature updates. And How to Start, Restart or Stop Background Intelligent Transfer Service using the command prompt etc.
Also, Read
- Fix We can’t find your camera error 0xA00F4244 on windows 10
- Stop Apps Running from Background in Windows 10
- Solved: Windows 10 High CPU usage after update !
- 3 Tweaks To increase USB Data Transfer Speed
- Quick tips to Fix Your DNS Server might be unavailable in Windows 10
Microsoft Windows Background Intelligent Transfer Service (BITS) is a service in Microsoft Windows operating systems (OSes) that allows download from and upload of files to Hypertext Transfer Protocol (HTTP) web servers and Server Message Block (SMB) file servers.
BITS uses idle network bandwidth to transfer files in the background or foreground so a user’s foreground experience is minimally impacted. Disabling the service prevents all applications that depend on BITS from automatically downloading programs and other important information.
BITS takes unused or idle network bandwidth to perform file transfers — downloads or uploads — from or to HTTP web servers and SMB file servers. The file transfers — say, between a client machine and server — are asynchronous and happen in the foreground or background. This means that, when an application requests BITS for a file transfer, it can freely perform any other task.
BITS includes PowerShell cmdlets for creating and managing transfers and the BITSAdmin command-line utility for creating download or upload jobs and monitoring their progress. The service also includes a queue administration facility to prioritize file transfer requests from applications.
If a disruption or interruption occurs on the network, BITS automatically reconnects and resumes the file transfer when the network or machine returns to service. BITS can pause and resume transfers automatically even after a reboot. It also transfers files when the machine is plugged in and in Modern Standby mode, thus remaining mindful of power usage.
Lifecycle of a Background Intelligent Transfer Service job
A BITS job is a container that holds one or more files to be transferred to or from HTTP web servers and SMB file servers. A job has properties that specify how BITS transfers the files and interacts with the application.
The job’s lifecycle begins with its creation. This is when the user specifies the job’s priority, whether it is an upload or download and for which events they want to receive notification(s). Once the job is created, files can be added to it — with a maximum of one file for upload jobs. The job properties can also be changed depending on the application. When adding one or more files to the job, it’s important to specify the file’s local (client) and remote (server) name.
When jobs are created, BITS automatically suspends jobs. The user must resume the job to activate it in the transfer queue, i.e., to move it from the suspended state to the queued state. It remains in the queued state until the BITS scheduler determines its turn to transfer files. At this point, the job moves to the connecting state, and BITS connects to the remote server. It then moves to the transferring state and remains there until one of four conditions occurs:
- The time slice ends.
- The transfer is complete.
- There is an error.
- The application suspends the job.
The job moves to the transferred state when BITS transfers all its files. The transferred files will only become available to the client when the application calls the IBackgroundCopyJob::Complete method and file ownership is transferred from BITS to the user.
How BITS preserves user experiences
Depending on the idle network bandwidth available, BITS increases or decreases the rate at which files are transferred. If an application starts consuming more bandwidth, BITS automatically decreases the file transfer rate, thus maintaining the user’s overall experience and ensuring that background transfers are optimal.
As long as the user who initiated the file transfer remains logged on to the network and a network connection is maintained, BITS continues to transfer files, even if the application itself exits. That said, BITS does not force a network connection if it is lost or if a user logs off. Instead, it first suspends the transfer job and then resumes it after the lost connection has been reestablished or after a logged-off user logs back in.
BITS always considers the cost of the file transfer and the network usage, as well as network congestion. Also, it uses app-specified transfer policies to prevent the transfer of files on costed network connections. These considerations particularly matter on roaming networks where costs can go up quickly. BITS also helps minimize the impact on — or interference with — the user’s foreground work, ultimately helping to preserve their experience working with the system.
Applications of Background Intelligent Transfer Service
BITS is most useful for system administrators looking to download files from or upload files to HTTP web servers and SMB file shares. In addition, it provides a Component Object Model interface that is useful for C, C++ and .NET programmers. Microsoft does not recommend the BITS application programming interface (API) for Universal Windows Platform programmers. They should use the Windows.Networking.BackgroundTransfer API instead.
Windows uses BITS to download updates to a user’s local system. Many other applications also use BITS, including applications that need to download from or upload files to an HTTP or representational state transfer web server or SMB file server. Applications that need to automatically resume file transfers after network disconnects or computer restarts also use BITS. Finally, BITS can be used to optimize wide area network traffic when used with BranchCache, a WAN optimization technology that is included in some editions of Windows and Windows Server OSes.
Types of transfer jobs and job states in BITS
BITS supports three types of transfer jobs:
- Download job. It downloads files to the client. Also, all files are transferred asynchronously in the foreground or background.
- Upload job. It uploads a file from the client to the server.
- Upload-reply job. It first uploads a file to the server and then receives a reply file from the server application that the upload has been completed.
A BITS job can be in one of four states:
- Starting. By default, the starting state is SUSPENDED. From this state, a user can add files to the job and also set job and file properties.
- Action. Multiple action states are possible that show the current internal activity of the job, such as QUEUED, CONNECTING and TRANSFERRING. Another action state is TRANSIENT ERROR, which indicates that the job failed to transfer the file.
- Transferred. This state happens when the transfer has succeeded and there’s no more transferring to be done.
- Final. The job is ACKNOWLEDGED and all completed downloaded files are available.
As a BITS job runs, it transitions between states in the different state classes. But, once it reaches a final state, it won’t move out of that state, meaning it’s not possible to call any state-changing methods. It also won’t show up in a job enumeration. If an error occurs, the job moves to the fatal error state (BITS cannot recover from it) or to the transient error state (the error may resolve itself and BITS retries the job until the transfer is successful or until the job times out within the application-specified period). If a job times out in the transient error state, BITS moves it to the fatal error state.
Background Intelligent Transfer Service priority levels
BITS can intelligently pick which transfer jobs to run and when. This is because the application can use different priority levels: one for the foreground and three for the background. A priority level determines when a transfer job is processed relative to other jobs in the transfer queue, so therefore:
- A higher-priority job takes precedence over a lower-priority job.
- Lower-priority jobs do not receive transfer time until all higher-priority jobs are transferred or are in an error state.
- Jobs at the same priority level share transfer time, so no large job can block the transfer queue and cause delays.
To schedule jobs at the same priority level, BITS uses round-robin scheduling, where each job is given a slice of time to process its files. If a particular job does not complete during its allotted time slice, it automatically goes back to the queued state, and the next job in the queue gets activated on a first-in, first-out (FIFO) basis. Here, it’s important to note that BITS does not guarantee FIFO processing, although it does its best.
In BITS 1.5 and earlier, foreground jobs are prioritized over background jobs. In fact, foreground jobs have the highest priority, and BITS only processes one job at a time. In later BITS versions, multiple foreground transfers can happen simultaneously, but multiple files in the same job are always transferred sequentially or serially.
The history of Background Intelligent Transfer Service
Microsoft has updated BITS a number of times:
- Microsoft introduced version 1.0 of BITS in Windows XP in 2001.
- Version 1.2 arrived in mid-2002 to add the Automatic Updates service to Windows 2000.
- Version 1.5 came in late 2003 with Windows Server 2003 and brought command-line support, more upload features and security improvements.
- Version 2.0, released in mid-2004 as an update for multiple OS deployments, added more download features, bandwidth throttling and support for SMB.
- Released in mid-2007, BITS 2.5 added support for IPv6 and custom HTTP headers and better HTTP security.
- BITS 3.0, included with Windows Vista and Windows Server 2008, added peer caching, notifications, temporary file access, HTTP redirect handling, additional Group Policy controls and event logging.
- BITS 4.0, released in mid-2009 with Windows 7 and Windows Server 2008 R2, brought token-based security, standalone file server features, refined bandwidth throttling and revised peer caching.
- BITS 5.0, included with Windows 10 in mid-2016, added improvements to background copy jobs, support for older background copy jobs and the ability to use BITS through APIs and PowerShell cmdlets.
- Version 10.1 of BITS, part of Windows 10 version 1703, also known as the Windows 10 Creators Update, refined download and notification features.
- Version 10.2 of BITS, part of the Windows 10 October 2018 Update, added default proxy ordering, as well as support for Modern Standby and mobile device manager policies and group policies.
- Version 10.3 of BITS, part of the Windows 10 May 2019 Update, enabled the ability to mark HTTP headers as write-only and server certificate validation callback.
Learn how to upload and download files with PowerShell File Transfer Protocol script, and read about eight secure file transfer services for the enterprise.
This was last updated in August 2023
Continue Reading About Microsoft Windows Background Intelligent Transfer Service (BITS)
- What is PowerShell and how to use it: The ultimate tutorial
- 5 steps to identify and fix Windows 11 performance issues
- Tools to transfer large files: How to find and buy the best
- Windows 11 migration tools for desktop administrators
- Windows 11 upgrade issues that desktop admins should know
Dig Deeper on IT operations and infrastructure management
-
What is JCL (job control language)?
By: TechTarget Contributor
-
How to use TFTP to transfer files across the network
By: Damon Garn
-
Use cURL and Wget to download network files from CLI
By: Damon Garn
-
uploading
By: Gavin Wright