Windows task scheduler api

About windows-task-scheduler-api

This is a lightweight library to deal with the Windows task scheduler from a Java application.

Every provided functionality relies, under the hood, on the schtasks.exe Windows command tool.

Which Java version do I need?

This library targets Java 8 or later.

Current version ☢️

The software is still in beta, especially because I need to test things thoroughly.

Usage

It’s as simple as using one of the classes provided into the cloud.martinodutto.wtsapi.api package, depending on which operation you need to perform.

For example, to query for the information concerning a specific task:

Query q = Query.of(LocalConfigurationParameters.getInstance());
List<Map<String, String>> taskInfos = q.queryForTask(myTaskName);

Implementations of the ConfigurationParameters interface will help you provide several custom parameters to deal with remote systems or special schtasks.exe paths.
Check out LocalConfigurationParameters if you just need to use the task scheduler from a local computer.

All the classes you need to use reflect the name of the operation that the Windows command will perform, so you will find:

Class Description
Delete Deletes one or more tasks
Run Immediately runs a scheduled task
End Stops a running scheduled task
Query Retrieves information for one or more tasks
Create ⚠️ Still working on it ⚠️
Change ⚠️ Still working on it ⚠️

Any of the previous objects can be created in just one way: using the of static method.

Dependency management

Even though this project is built with Maven, this library is still unavailable on any public repository. 😢

So you’ll have to build it by yourself.
But don’t panic! I am planning to deploy it somewhere, as soon as I can. 😉

Contributing

Pull requests are welcome!

From Wikipedia, the free encyclopedia

Windows Task Scheduler

Management console for Task Scheduler 3.0 in Windows 11

Other names taskschd.msc
Developer(s) Microsoft
Initial release 1995; 30 years ago
Written in C++
Included with
  • Internet Explorer 4.0 and later
    (Windows 95 and Windows NT 4.0)
  • Windows 98 and later
    (Windows 9x family)
  • Windows 2000 and later
    (Windows NT family)
  • ReactOS
    (Windows NT-like)
Predecessor System Agent
Service name Task Scheduler (Schedule)
Type Windows service
Website docs.microsoft.com/en-us/windows/win32/taskschd/task-scheduler-start-page 

Task Scheduler (formerly Scheduled Tasks)[1] is a job scheduler in Microsoft Windows that launches computer programs or scripts at pre-defined times or after specified time intervals.[2][3] Microsoft introduced this component in the Microsoft Plus! for Windows 95 as System Agent.[4] Its core component is an eponymous Windows service.[5] The Windows Task Scheduler infrastructure is the basis for the Windows PowerShell scheduled jobs feature introduced with PowerShell v3.[6]

Task Scheduler can be compared to cron or anacron on Unix-like operating systems. This service should not be confused with the scheduler, which is a core component of the OS kernel that allocates CPU resources to processes already running.

Task Scheduler 1.0 is included with Windows NT 4.0[7] (with Internet Explorer 4.0 or later), Windows 2000,[7] Windows XP[8] and Windows Server 2003.[9] It runs as a Windows Service, and the task definitions and schedules are stored in binary .job files. Tasks are manipulated directly by manipulating the .job files. Each task corresponds to single action. On Windows 95 (with Internet Explorer 4.0 or later), Windows 98 and Windows Me, the Task Scheduler runs as an ordinary program, mstask.exe. It also displays a status icon in the notification area on Windows 95 and Windows 98 and runs as a hidden service on Windows Me, but can be made to show a tray icon.[1] Computer programs and scripts can access the service through six COM interfaces.[10] Microsoft provides a scheduling agent DLL, a sample VBScript and a configuration file to automate Task Scheduler.[11]

In addition to the graphical user interface for Task Scheduler in Control Panel, Windows provides two command-line tools for managing scheduled task: at.exe (deprecated)[12] and schtasks.exe.[5][13][14] However, at.exe cannot access tasks created or modified by Control Panel or schtasks.exe.[15] Also, tasks created with at.exe are not interactive by default; interactivity needs to be explicitly requested. The binary «.job» files which the AT command produces are stored in the %WINDIR%\Tasks directory.[16][17]

Task Scheduler 2.0 was introduced with Windows Vista[18] and included in Windows Server 2008 as well.[19][9] The redesigned Task Scheduler user interface is now based on Management Console. In addition to running tasks on scheduled times or specified intervals, Task Scheduler 2.0 also supports calendar and event-based triggers, such as starting a task when a particular event is logged to the event log, or when a combination of events has occurred. Also, several tasks that are triggered by the same event can be configured to run either simultaneously or in a pre-determined chained sequence of a series of actions, instead of having to create multiple scheduled tasks. Tasks can also be configured to run based on system status such as being idle for a pre-configured amount of time, on startup,[20] logoff, or only during or for a specified time. XPath expressions can be used to filter events from the Windows Event Log. Tasks can also be delayed for a specified time after the triggering event has occurred, or repeat until some other event occurs. Actions that need to be done if a task fails can also be configured. The actions that can be taken in response to triggers, both event-based as well as time-based, not only include launching applications but also take a number of custom actions. Task Scheduler includes a number of actions built-in, spanning a number of applications; including send an e-mail, show a message box, or fire a COM handler when it is triggered. Custom actions can also be specified using the Task Scheduler API. Task Scheduler keeps a history log of all execution details of all the tasks.[21] Windows Vista uses Task Scheduler 2.0 to run various system-level tasks;[22] consequently, the Task Scheduler service can no longer be disabled (except with a simple registry tweak).

Task Scheduler 2.0 in Windows 7

Task Scheduler 2.0 exposes an API to allow computer programs and scripts create tasks.[19][23] It consists of 42 COM interfaces.[24] The Windows API does not, however, include a managed wrapper for Task Scheduler though an open source implementation exists.[25] The job files for Task Scheduler 2.0 are XML-based, and are human-readable, conforming to the Task Scheduler Schema.[19][23]

  • New security features, including using Credential Manager to passwords for tasks on workgroup computers and using Active Directory for task credentials on domain-joined computers so that they cannot be retrieved easily. Also, scheduled tasks are executed in their own session, instead of the same session as system services or the current user.
  • Ability to wake up a machine remotely or using BIOS timer from sleep or hibernation to execute a scheduled task or run a previously scheduled task after a machine gets turned on.
  • Ability to attach tasks to events directly from the Event Viewer.

The Task Scheduler service works by managing Tasks; Task refers to the action (or actions) taken in response to trigger(s). A task is defined by associating a set of actions, which can include launching an application or taking some custom-defined action, to a set of triggers, which can either be time-based or event-based. In addition, a task also can contain metadata that defines how the actions will be executed, such as the security context the task will run in. Tasks are serialized to .job files and are stored in the special folder titled Task Folder, organized in subdirectories. Programmatically, the task folder is accessed using the ITaskFolder interface or the TaskFolder scripting object and individual tasks using the IRegisteredTask interface or RegisteredTask object.[26]

Column ‘Last Result’

[edit]

The Last Result column displays a completion code. The common codes for scheduled tasks are:[27][28]

  • 0 or 0x0: The operation completed successfully.
  • 1 or 0x1: Incorrect function called or unknown function called.
  • 2 or 0x2: File not found.
  • 10 or 0xa: The environment is incorrect.
  • 0x00041300: Task is ready to run at its next scheduled time.
  • 0x00041301: The task is currently running.
  • 0x00041302: The task has been disabled.
  • 0x00041303: The task has not yet run.
  • 0x00041304: There are no more runs scheduled for this task.
  • 0x00041305: One or more of the properties that are needed to run this task have not been set.
  • 0x00041306: The last run of the task was terminated by the user.
  • 0x00041307: Either the task has no triggers or the existing triggers are disabled or not set.
  • 0x00041308: Event triggers do not have set run times.
  • 0x80010002: Call was canceled by the message filter
  • 0x80041309: A task’s trigger is not found.
  • 0x8004130A: One or more of the properties required to run this task have not been set.
  • 0x8004130B: There is no running instance of the task.
  • 0x8004130C: The Task Scheduler service is not installed on this computer.
  • 0x8004130D: The task object could not be opened.
  • 0x8004130E: The object is either an invalid task object or is not a task object.
  • 0x8004130F: No account information could be found in the Task Scheduler security database for the task indicated.
  • 0x80041310: Unable to establish existence of the account specified.
  • 0x80041311: Corruption was detected in the Task Scheduler security database
  • 0x80041312: Task Scheduler security services are available only on Windows NT.
  • 0x80041313: The task object version is either unsupported or invalid.
  • 0x80041314: The task has been configured with an unsupported combination of account settings and run time options.
  • 0x80041315: The Task Scheduler Service is not running.
  • 0x80041316: The task XML contains an unexpected node.
  • 0x80041317: The task XML contains an element or attribute from an unexpected namespace.
  • 0x80041318: The task XML contains a value which is incorrectly formatted or out of range.
  • 0x80041319: The task XML is missing a required element or attribute.
  • 0x8004131A: The task XML is malformed.
  • 0x0004131B: The task is registered, but not all specified triggers will start the task.
  • 0x0004131C: The task is registered, but may fail to start. Batch logon privilege needs to be enabled for the task principal.
  • 0x8004131D: The task XML contains too many nodes of the same type.
  • 0x8004131E: The task cannot be started after the trigger end boundary.
  • 0x8004131F: An instance of this task is already running.
  • 0x80041320: The task will not run because the user is not logged on.
  • 0x80041321: The task image is corrupt or has been tampered with.
  • 0x80041322: The Task Scheduler service is not available.
  • 0x80041323: The Task Scheduler service is too busy to handle your request. Please try again later.
  • 0x80041324: The Task Scheduler service attempted to run the task, but the task did not run due to one of the constraints in the task definition.
  • 0x00041325: The Task Scheduler service has asked the task to run.
  • 0x80041326: The task is disabled.
  • 0x80041327: The task has properties that are not compatible with earlier versions of Windows.
  • 0x80041328: The task settings do not allow the task to start on demand.
  • 0x80070002: The Task Scheduler cannot find the file.
  • 0x800710E0: The operator or administrator has refused the request.
  • 0xC000013A: The application terminated as a result of a CTRL+C.
  • 0xC0000142: The application failed to initialize properly.

On Windows 2000 and Windows XP, when a computer is prepared for disk imaging with the sysprep utility, it cannot run tasks configured to run in the context of the SYSTEM account. Sysprep changes the security identifier (SID) to avoid duplication but does not update scheduled tasks to use the new SID. Consequently, the affected tasks fail to run. There is no solution for this problem but one may reschedule the affected tasks to work around the issue.[29]

On Windows Vista or Windows Server 2008, the next execution time displayed in Task Scheduler may be wrong. Microsoft issued a hotfix to remedy this issue.[30]

  • cron, job scheduler for Unix-like operating systems
  1. ^ a b «How to Enable the Scheduled Tasks Icon in Windows Me». Support. Microsoft. January 29, 2007. Archived from the original on January 30, 2008.
  2. ^ «Keep your Windows desktop in shape with Task Scheduler». TechRepublic. January 4, 2002.
  3. ^ «What is Task Scheduler?». Computer Hope. November 30, 2020.
  4. ^ Al Fasoltd (March 29, 1998). «Windows 98: Stable and fast, as well as ‘new and improved’«. The Syracuse Newspapers. Retrieved October 6, 2007.
  5. ^ a b Mueller, John Paul (2010). Windows Command Line Administration Instant Reference. John Wiley & Sons. ISBN 978-0470930908.
  6. ^ Warner, Timothy L. (2015). Sams Teach Yourself Windows PowerShell in 24 Hours. Sams Publishing. ISBN 978-0134049359.
  7. ^ a b Burnett, Mark; Amaris, Chris; Doyle, Chris; Locher, L. J.; Morimoto, Rand (2002). Maximum Windows 2000 Security. Sams Publishing. ISBN 978-0672319655.
  8. ^ Mueller, John Paul (2001). Sams Teach Yourself Microsoft Windows XP in 21 Days. Sams Publishing. ISBN 978-0132715539.
  9. ^ a b «About the Task Scheduler». MSDN. Microsoft. Retrieved October 6, 2007.
  10. ^ «Task Scheduler 1.0 Interfaces». MSDN. Microsoft. Retrieved May 30, 2014.
  11. ^ «Task Scheduler Using VBScript». Download Center. Microsoft. March 22, 2004. Archived from the original on May 4, 2006.
  12. ^ «MS-DOS and Windows command line at command». Computer Hope. Retrieved March 7, 2021.
  13. ^ «Schtasks». Microsoft TechNet. Microsoft. Retrieved May 18, 2014.
  14. ^ «At». Microsoft TechNet. Microsoft. Retrieved May 18, 2014.
  15. ^ «How To Use the AT Command to Schedule Tasks». Support. Microsoft. October 30, 2006.
  16. ^ Kleiman, Dave; Hunter, Laura E (2006). Winternals Defragmentation, Recovery, and Administration Field Guide. Elsevier. ISBN 978-0080489872.
  17. ^ «Applications Started with AT Are Not Interactive». Support. Microsoft. February 20, 2007. Archived from the original on October 29, 2004.
  18. ^ Cowart, Robert; Knittel, Brian (2008). Special Edition Using Microsoft Windows Vista. Que Publishing. ISBN 978-0789737816.
  19. ^ a b c Kingsley-Hughes, Adrian; Kingsley-Hughes, Kathie; Read, Daniel (2011). VBScript Programmer’s Reference. John Wiley & Sons. ISBN 978-1118058695.
  20. ^ Paul, Ian (September 5, 2014). «Automate your morning programs with Windows Task Scheduler». PCWorld. Retrieved March 15, 2021.
  21. ^ «Windows Vista Task Scheduler». Microsoft TechNet. Microsoft. March 3, 2006. Archived from the original on April 12, 2006. Retrieved April 24, 2006.
  22. ^ «Description of the scheduled tasks in Windows Vista». August 24, 2007. Archived from the original on October 22, 2007.
  23. ^ a b Kenny Kerr (October 2007). «Task Scheduler 2.0». MSDN. Microsoft. Archived from the original on December 26, 2007. Retrieved October 6, 2007.
  24. ^ «Task Scheduler 2.0 Interfaces». MSDN. Microsoft. Retrieved May 30, 2014.
  25. ^ «C# API for Task Scheduler 2.0». Stack Overflow. Retrieved July 24, 2019.
  26. ^ «Tasks (Windows)». MSDN. Microsoft. Retrieved October 6, 2007.
  27. ^ «How to troubleshoot scheduled tasks in Windows XP and in Windows Server 2003». Support. Microsoft. May 22, 2013. Retrieved September 3, 2013.
  28. ^ «Task Scheduler Error and Success Constants». MSDN. Microsoft.
  29. ^ «Scheduled tasks may not start if you used a System Preparation image to install Windows XP or Windows 2000». Support. Microsoft. July 1, 2004. Archived from the original on September 26, 2008. Retrieved May 19, 2012.
  30. ^ «The value in the Next Run Time field in Task Scheduler is incorrect in Windows Vista and in Windows Server 2008». Support. Microsoft. October 15, 2008. Archived from the original on December 11, 2008.
  • Leonhard, Woody; Rusen, Ciprian (2021). Windows 10 All-in-One For Dummies. John Wiley & Sons. ISBN 978-1119680574.
  • Knittel, Brian; McFedries, Paul (2014). Windows 8.1 in Depth. Que Publishing. ISBN 978-0789752819.
  • Bott, Ed; Siechert, Carl; Stinson, Craig (2009). Windows 7 Inside Out. Pearson Education. ISBN 978-0735636842.
  • Ruest, Danielle; Ruest, Nelson (2008). Microsoft Windows Server 2008: The Complete Reference. McGraw-Hill Education. ISBN 978-0071596466.
  • Cowart, Robert; Knittel, Brian (2008). Special Edition Using Microsoft Windows Vista. Que. ISBN 978-0789737816.
  • Task Scheduler on MSDN
  • The Log File in the Task Scheduler May Be Incorrectly Formatted and Difficult to Read — Archived October 16, 2007, at the Wayback Machine
  • Unable to Delete Text in the Task Scheduler Log File
  • Task Scheduler Service Does Not Start
  • Scheduled Program Does Not Start in Task Scheduler — Archived August 21, 2006, at the Wayback Machine
  • Cannot Disable Task Scheduler

Are you tired of manually performing repetitive tasks on your Windows system? Do you want to streamline your workflow and save time? Look no further than Windows Task Scheduler, the built-in job scheduling tool in Windows. Whether you’re a developer, IT professional, or just someone looking to automate some basic tasks, this guide will provide you with everything you need to know to get started with Task Scheduler.

Understanding Task Scheduler and its Features

Task Scheduler is a built-in utility in Windows operating systems that allows users to schedule tasks and automate routine tasks on their computer. Some of the key features and benefits of Task Scheduler include the ability to schedule tasks to run at a specific time or when a specific event occurs, the ability to create complex tasks with multiple triggers and actions, and the ability to automate tasks using PowerShell scripts. Task Scheduler also provides detailed logging and notification features to help users monitor and troubleshoot their tasks.

Task Scheduler has been a standard component of Windows since Windows 98, and is supported on all modern versions of Windows, including Windows 10, Windows Server, and Windows Nano Server. While there are other job scheduling software options available, Task Scheduler is unique in that it is included with the operating system and does not require any additional software installation.

To effectively use Task Scheduler, it is important to understand some basic terminology such as tasks, triggers, actions, and conditions. A task is a set of instructions that describe what needs to be done, while a trigger is an event or condition that initiates the task. An action is the actual task that is performed, and a condition is a set of requirements that must be met before the task can be executed.

Creating Basic Tasks with Task Scheduler

One of the most common uses of Task Scheduler is to create basic tasks that automate routine tasks such as running backups or cleaning up files. Creating a basic task is easy using the Create Basic Task Wizard, which guides users through the process of setting up a new task.

To create a new task, users can open Task Scheduler and select the “Create Basic Task” option from the Action menu. The wizard will then prompt users to enter a name and description for the task, as well as select a trigger for when the task should run. Users can choose from a variety of triggers such as daily, weekly, or monthly, or they can set a specific time or event trigger.

Once the trigger has been set, users can then select the appropriate action for the task. This can include running a program, sending an email, displaying a message, or even starting a PowerShell script. After the action has been configured, users can review and test the task to ensure that it runs as expected.

In the event that a basic task encounters an issue or error, Task Scheduler provides detailed logging and notification features to help users troubleshoot the problem. By reviewing the task history and error logs, users can quickly identify and resolve any issues with their tasks.

Advanced Task Scheduling Techniques

Task Scheduler is a powerful tool that can handle a variety of tasks, from simple to complex. Here are some advanced techniques to help you get the most out of Task Scheduler:

Using the Task Scheduler API to create complex tasks: The Task Scheduler API allows you to create tasks programmatically using C++, C#, or Visual Basic. This can be useful if you need to create tasks dynamically or if you want to create tasks with complex triggers.

Working with batch files and PowerShell scripts: Task Scheduler can run batch files and PowerShell scripts as part of a task. This can be useful for automating tasks that require a series of commands or scripts to run.

Setting dependencies and prioritizing tasks: You can set up dependencies between tasks so that one task runs only after another task has completed. You can also prioritize tasks so that high-priority tasks run before low-priority tasks.

Configuring notifications and logging: Task Scheduler can send email notifications when a task completes or when an error occurs. You can also configure logging to keep track of task activity and diagnose problems.

Cross-platform workflows with Task Scheduler: While Task Scheduler is a Windows-specific tool, it can be used in conjunction with other tools to create cross-platform workflows. For example, you can use Task Scheduler to trigger a PowerShell script that runs on a Linux server.

Visualcron vs. Task Scheduler

Visualcron is a commercial job scheduling software that offers additional features and capabilities beyond those of Task Scheduler. Here’s a comparison of the two tools:

Overview of Visualcron job scheduling software: Visualcron is a powerful job scheduling software that includes features such as a drag-and-drop interface, ETL (Extract, Transform, Load) capabilities, and file transfer functionality.

Comparison of features and benefits to Task Scheduler: Visualcron offers many features that are not available in Task Scheduler, such as the ability to create complex workflows, run tasks on remote computers, and monitor task performance in real-time. However, Task Scheduler is a built-in tool in Windows and is therefore more widely available.Use cases for Visualcron vs. Task Scheduler: Visualcron is a good choice for organizations that need a robust job scheduling solution with advanced features. Task Scheduler is a good choice for smaller organizations or individuals who need basic scheduling capabilities built into Windows.


Frequently Asked Questions

What are the differences between Windows Task Scheduler and cron jobs?

Windows Task Scheduler and cron jobs are both used to schedule and automate tasks, have some key differences in functionality and how they work. 

The main difference between the two include the platform they run on. Windows Task Scheduler is a built-in utility in Windows operating systems, whereas cron jobs are a command-line tool used on Unix-based operating systems. Other differences include syntax, granularity, job dependency, job logging, and portability.  

ActiveBatch’s cross-platform job scheduling software is perfect for teams working to orchestrate diverse systems.

How do I schedule a job in Windows?

To schedule a job in Windows using ActiveBatch, take the following steps:

1. Open ActiveBatch and navigate to the “Jobs” tab. 
2. Click the “New” button to create a new job. 
3. Provide the job name and description in the “General” tab. 
4. Define the steps for the job in the “Steps” tab. You can add one or more steps, and each step can be a command, script, or executable file.
5. Set conditions for the job to run in the “Conditions” tab. You can specify a time window during which the job can run, or configure the job to run based on a specific event or condition.
6. Configure the job schedule in the “Schedules” tab. You can specify the date and time when the job should run, as well as the frequency of the job.
7. Configure notifications for the job in the “Notifications” tab. You can specify email notifications for job status changes, failures, and other events.
8. Save the job by clicking the “Save” button. 

Once the job is saved, it will appear in the ActiveBatch Jobs list. You can then run the job manually or let it run automatically according to the schedule you have set.

Learn about ActiveBatch’s support for integrations and extensions for automating across your entire IT environment.

What is ActiveBatch and how does it differ from other workload automation software?

ActiveBatch is a powerful workload automation software that allows you to automate tasks and workflows across multiple applications, platforms, and environments, including Microsoft Windows, Unix, and macOS. Compared to other scheduling options like cron, the advanced task scheduler offers a more comprehensive and extensible solution that can handle simple tasks as well as complex, multi-step workflows.

Dig into what makes ActiveBatch different.

How do I schedule automated tasks in ActiveBatch?

To schedule automated tasks in ActiveBatch, you need to create a job that defines the task or workflow you want to automate, then specify when and how often the job should run. You can set the schedule to run on a specific day or time, on a recurring basis, or when certain conditions are met. You can also use the Action tab to specify what action should be taken when the job runs, such as executing an exe or command line.

Learn events-based and dependencies-based task automation.

Can I use ActiveBatch for DevOps automation?

Yes, ActiveBatch is an excellent tool for DevOps automation, as it provides a centralized platform for managing and scheduling automated tasks across multiple environments and applications. This can help streamline your development processes and ensure that your software is deployed and tested in a consistent and reliable way.

Get the latest on ActiveBatch for DevOps.

How does ActiveBatch Windows Task Scheduler compare to other scheduling options like cron?

Compared to other scheduling options like cron, the Windows Task Scheduler from ActiveBatch offers a more comprehensive and extensible solution that can handle more complex workflows and integrate with a wider range of applications and platforms. It also provides a more user-friendly interface and more advanced features like the Action tab and the ability to schedule jobs based on specific events or conditions.

Compare Windows job scheduling to other options.

Can I use ActiveBatch for on-premises and SaaS applications?

Yes, ActiveBatch can be used to automate tasks and workflows across both on-premises and SaaS applications. It supports a wide range of applications and platforms out-of-the-box, and can also be extended to integrate with custom applications and platforms using the API or other extensibility options.

See how ActiveBatch works for on-premises applications.

Can I use ActiveBatch to schedule tasks across multiple operating systems?

Yes, ActiveBatch is designed to support task scheduling across multiple operating systems, including Microsoft Windows, Unix, and macOS. This can help you manage your workload automation tasks in one centralized location, regardless of the underlying platform or application.

Experience the impact of task scheduling with ActiveBatch.

Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

  • Home

  • Forums

  • Software

  • Programmers

  • Development Methodologies and Architecture

  • Win API (Microsoft)

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Task Scheduler API?

1


  • Thread starter

    vbtutor


  • Start date

Status
Not open for further replies.

  • #1


I need to either find the path and file structure/format information that Windows Task Scheduler uses to run Scheduled Tasks so that I can create a file that the Task Scheduler will automatically read and process. Or have an API call to the scheduler from within Visual Basic 6.0 so that automated processes I am creating in an application will get run.

Any suggestions?

Thanks,

David

  • #2


Hi

You can use the Win32’s NetScheduleJobAdd().

Taken from the Win32 documentation:
The NetScheduleJobAdd function submits a job to run at a specified future time and date. This function requires that the schedule service be started at the computer to which the job is submitted.

    1

  • Thread starter
  • #3


That’s not exactly what I’m looking for, but thanks.. I looked up the NetScheduleJobAdd() function at msdn, and it appears to be a C++ function. I am using VB 6.0.

I think I did find what I’m looking for though.

Thanks again.

  • #4


vbtutor

can you post whatr you found? Attitude is Everything

  • Thread starter
  • #5


I found a VB example at planet source code. Here’s what I found:

Option Explicit
‘ Schedule api’s
Declare Function NetScheduleJobAdd Lib &quot;netapi32.dll&quot; _
(ByVal Servername As String, Buffer As Any, Jobid As Long) As Long

‘ Schedule structure
Type AT_INFO
JobTime As Long
DaysOfMonth As Long
DaysOfWeek As Byte
Flags As Byte
dummy As Integer
Command As String
End Type

‘ Schedule constants
Const JOB_RUN_PERIODICALLY = &H1
Const JOB_NONINTERACTIVE = &H10
Const NERR_Success = 0

Private Sub Command1_Click()
Dim lngWin32apiResultCode As Long
Dim strComputerName As String
Dim lngJobID As Long
Dim udtAtInfo As AT_INFO

‘ Convert the computer name to unicode
strComputerName = StrConv(Text1.Text, vbUnicode)

‘ Setup the tasks parameters
SetStructValue udtAtInfo

‘ Schedule the task
lngWin32apiResultCode = NetScheduleJobAdd(strComputerName, udtAtInfo, lngJobID)

‘ Check if the task was scheduled
If lngWin32apiResultCode = NERR_Success Then
MsgBox &quot;Task&quot; & lngJobID & &quot; has been scheduled.&quot;
End If

End Sub
Private Sub SetStructValue(udtAtInfo As AT_INFO)
Dim strTime As String
Dim strDate() As String
Dim vntWeek() As Variant
Dim intCounter As Integer
Dim intWeekCounter As Integer

vntWeek = Array(&quot;M&quot;, &quot;T&quot;, &quot;W&quot;, &quot;TH&quot;, &quot;F&quot;, &quot;S&quot;, &quot;SU&quot

With udtAtInfo

‘ Change the format of the time
strTime = Format(Text2.Text, &quot;hh:mm&quot

‘ Change the time to one used by the api
.JobTime = (Hour(strTime) * 3600 + Minute(strTime) * 60) * 1000

‘ Set the Date parameters
If Val(Text3.Text) > 0 Then

‘ Set the task to run on specific days of the month i.e. 9th & 22nd of the month
strDate = Split(Text3.Text, &quot;,&quot
For intCounter = 0 To UBound(strDate)
.DaysOfMonth = .DaysOfMonth + 2 ^ (strDate(intCounter) — 1)
Next

Else

‘ Set the task to run on sepecific days of the week i.e. Monday & Thursday
strDate = Split(Text3.Text, &quot;,&quot
For intCounter = 0 To UBound(strDate)
For intWeekCounter = 0 To UBound(vntWeek)
If UCase(strDate(intCounter)) = vntWeek(intWeekCounter) Then
.DaysOfWeek = .DaysOfWeek + 2 ^ intWeekCounter
Exit For
End If
Next
Next
End If

‘ Set the interactive property
If Check1.Value = vbUnchecked Then
.Flags = .Flags Or JOB_NONINTERACTIVE
End If

‘ Set to run periodically
If Option2.Value = True Then
.Flags = .Flags Or JOB_RUN_PERIODICALLY
End If

‘ Set the command to run
.Command = StrConv(Text4.Text, vbUnicode)
End With
End Sub

  • #6


thank you Attitude is Everything

  • Thread starter
  • #7


This code example works just fine at creating a scheduled job in Windows Task Scheduler, but one thing it doesn’t do is check to see if the job is already scheduled. So if you wanted to have the ability to change your schedule, then you simply create another job with this code, rather than overwriting it.

Any ideas on how to read the current job, and overwrite it, or delete it when creating/changing the schedule?

thanks..

  • #8


In teh dependency list for WinAt are listed

NetScheduleJobAdd
NetScheduleJobDel
NetScheduleJobEnum
NetScheduleJobGetInfo

If you poke about where you found the Add oyu should find the others, with a bit of luck.

  • #9


Hi,
The &quot;NetScheduleJobAdd&quot; does work in winxp with vb6 but
the &quot;NetScheduleJobEnum&quot; api doesn’t. What can i do ???

  • #10


What do the textX.text fields refer to in the above code?

Thanks and have a great day!

  • #11


I cleaned up the above code from PSC and made it so you can just paste it into a function, i did have trouble coping and pasting the above code, the vb6 ide made everything error syntax even tho it was correct. I just retyped it letter for letter without a problem

Public Declare Function NetScheduleJobAdd Lib &quot;netapi32.dll&quot; (ByVal Servername As String, Buffer As Any, Jobid As Long) As Long
Public Declare Function NetScheduleJobDel Lib &quot;netapi32.dll&quot; (ByVal Servername As String, minJobId As Long, maxJobId As Long) As Long
Public Declare Function GetComputerName Lib &quot;kernel32&quot; Alias &quot;GetComputerNameA&quot; (ByVal lpBuffer As String, nSize As Long) As Long

‘ Schedule structure
Private Type AT_INFO
JobTime As Long
DaysOfMonth As Long
DaysOfWeek As Byte
Flags As Byte
dummy As Integer
command As String
End Type

Public Sub Create_Scheduled_Event(t As String, d As String, c As String, Optional i As Boolean = False, Optional p As Boolean = True)
Dim strTime As String
Dim strDate() As String
Dim vntWeek() As Variant
Dim intCounter As Integer
Dim intWeekCounter As Integer
Dim at As AT_INFO
Dim lngJobID As Long
Dim lngWin32apiResultCode As Long
Dim strComputerName As String

strComputerName = StrConv(Get_Computer_Name, vbUnicode)

err.Clear

vntWeek = Array(&quot;M&quot;, &quot;T&quot;, &quot;W&quot;, &quot;TH&quot;, &quot;F&quot;, &quot;S&quot;, &quot;SU&quot

With at
strTime = Format(t, &quot;hh:mm&quot
.JobTime = (Hour(strTime) * 3600 + Minute(strTime) * 60) * 1000
If Val(d) > 0 Then
strDate = Split(d, &quot;,&quot
For intCounter = 0 To UBound(strDate)
.DaysOfMonth = .DaysOfMonth + 2 ^ (strDate(intCounter) — 1)
Next
Else
strDate = Split(d, &quot;,&quot
For intCounter = 0 To UBound(strDate)
For intWeekCounter = 0 To UBound(vntWeek)
If UCase(strDate(intCounter)) = vntWeek(intWeekCounter) Then
.DaysOfWeek = .DaysOfWeek + 2 ^ intWeekCounter
End If
Next
Next
End If

If i = False Then .Flags = .Flags Or JOB_NONINTERACTIVE

If p = True Then .Flags = .Flags Or JOB_RUN_PERIODICALLY

.command = StrConv(c, vbUnicode)
End With

lngWin32apiResultCode = NetScheduleJobAdd(strComputerName, at, lngJobID)

If lngWin32apiResultCode = NERR_Success Then MsgBox &quot;Task &quot; & lngJobID & &quot; has been scheduled.&quot;
End Sub

Public Function Get_Computer_Name() As String
Dim pc_name As String
pc_name = String(50, Chr(0))
GetComputerName pc_name, 50 ‘gets the comp. name
Get_Computer_Name = &quot;\\&quot; & Trim(pc_name)
End Function

i was having trouble with NetScheduleJobDel it returns error code 3806 and on the system error code page that error number isn’t listed.

-Xodus

ps. hope i didn’t forget anything

  • #12


I wrote the code on planet source to use NetScheduleJobAdd that vbtutor (Programmer) printed, if you want help on it just mail me and I will show you how to use it.

  • Thread starter
  • #13


It’s nice to see that this thread is still alive and active. Thanks Xodus for cleaning up the code a bit, and thanks to Giddo for offering to help.

I also found some references that allow you to access the task scheduler API through a command shell interface using the AT command. This is only valid for Windows NT/2k/XP, just as the NetScheduleJob* functions are. Sorry I don’t have a good example handy. The references I found are actually in a PHP book, and I can’t seem to find anything on MSDN about this.

The big question though, is where to find an API reference on how to create scheduled tasks on Windows 9.x/Me. I know it’s possible, because Symantec does this for NAV on the Win 9.x/Me platform for their Live Update application, but I’ve not seen anything on how to achieve this.

Any suggestions?

Thanks,

David

  • #14


Have you guys seen the Task Scheduler API here:
I don’t thing that it allows the scheduling of tasks on remote PC’s but it is a fully documented API.

  • #15


OOPS!

I posted the wrong URL:

  • #16


Hi all

Is this what I’ve been looking for? I really need a solid scheduler I can install as a service — the requirements for the use of it, is as follows:

— 2 different Executables to be run.
— one every 10 minutes
— and one every hour

I admit at once… I’m the worlds greates newbie in this VB show, and would appreciate some code examples — and some how to do’s…

;o)
Regards
Flemming

  • #17


C’d someone pl. post how to declare and call the following netschedule related functions.

GetNetScheduleAccountInformation
SetScheduleAccountInformation
NetScheduleJobEnum

Thanks
-deepika

  • #18


Hi Giddo

Can u please tell me how to schedule a task daily & set its advanced properties like setting repeat task details?
Code sample in VB will be highly appreciated..

Thanks..
eCGSoft

  • #19


I got the roots of the following code from a co-worker so I can’t take credit. It uses the WMI interface to the scheduler service. It can be used to schedule a task at a predefined interval. The following code is dependent on a predifined global date which is used to hold the time of day for the task to be run. I use this to run a task every 15 minutes.

Usage:

1) Schedule your program to run &quot;on startup&quot; in the task sceduler via the GUI interface. Assign an admin, or other appropriate user context for it to run under.

2) In your program, (MyApp.exe)

…do something
‘ Set the start time to 15 minutes from now
gdtProcessTime = DateAdd(&quot;n&quot;,15,Now())
…do something
‘ Have the program reschedule itself for 15 minutes later
NTTaskDelete App.Path & &quot;\MyApp.exe&quot;
NTTaskCreate App.Path & &quot;\MyApp.exe&quot;

End

This sequence starts the app under the user account that is specified by the &quot;startup&quot; event. Since the program is using this account when it runs the new event that is &quot;re-scheduled&quot; uses the same user acount(default) to run under.

The &quot;Exists&quot; function at the end is not used in this sample but is useful sometimes.

Hope this is useful.
‘———————————

Public dtProcessTime as date

Private Sub NTTaskDelete(strCmdLine As String)

‘ this connects to the NT Task Scheduler via WMI to determine if the desired NT Scheduled Task Exists
‘ if found, it deletes it

Dim objTasks As Object
Dim objTask As Object
Dim strErr As String

On Error Resume Next
‘ now connect to NT Task Scheduler to determine if the script is scheduled
‘ create and schedule it if necessary
Set objTasks = GetObject(&quot;winmgmts:{impersonationLevel=impersonate}&quot.InstancesOf(&quot;Win32_ScheduledJob&quot
If Err Then
strErr = &quot;: &quot; & Err.Number & &quot; &quot; & Err.Source & &quot; &quot; & Err.Description
App.LogEvent &quot;NTTaskDelete: Could not delete the NT Task for &quot; & strCmdLine & &quot; due to error connecting to WMI: &quot; & strErr, vbLogEventTypeWarning
Err.Clear
Exit Sub
End If

For Each objTask In objTasks
If UCase(objTask.Command) = UCase(strCmdLine) Then
‘ but if trap error if trying to delete
Err.Clear
objTask.Delete
If Err Then
strErr = &quot;: &quot; & Err.Number & &quot; &quot; & Err.Source & &quot; &quot; & Err.Description
App.LogEvent &quot;NTTaskDelete: Could not delete the NT Task for &quot; & strCmdLine & &quot; due to error during delete: &quot; & strErr, vbLogEventTypeWarning
Err.Clear
End If
Exit For
End If
Next

End Sub

Private Sub NTTaskCreate(strCmdLine As String)

Dim objList As Object
Dim objTask As Object
Dim strTime As String
Dim ret As Long
Dim strResult As String
Dim intJobID As Integer
Dim intNextHour As Integer
Dim intNextMinute As Integer
Dim strTimeOffset As String

‘ gdtProcessTime has already been incremented to the next start time
‘ determine which is the next hour for task to execute
intNextHour = DatePart(&quot;h&quot;, gdtProcessTime)
intNextMinute = DatePart(&quot;n&quot;, gdtProcessTime)
‘ example
‘ strTime = &quot;********123000.000000-420&quot;
‘ set it for real
‘ determine UCT Offset for this computer (Universal Coordinated Time)
‘ Note that there’s always only 1 Win32_ComputerSystem obj, but have to use for-next anyway
Set objList = GetObject(&quot;winmgmts:{impersonationLevel=impersonate}&quot.InstancesOf(&quot;Win32_ComputerSystem&quot
For Each objTask In objList
strTimeOffset = Trim$(objTask.CurrentTimeZone)
Exit For
Next
Set objTask = Nothing
Set objList = Nothing

strTime = &quot;********&quot; & Format$(intNextHour, &quot;00&quot & Format$(intNextMinute, &quot;00&quot & &quot;00&quot; & &quot;.000000&quot; & strTimeOffset ‘ -300&quot;
Set objTask = GetObject(&quot;winmgmts:{impersonationLevel=impersonate}!Win32_ScheduledJob&quot

ret = objTask.Create(strCmdLine, strTime, False, , , False, intJobID)

Select Case ret
Case 0
strResult = &quot;The request is accepted.&quot;
Case 1
strResult = &quot;The request is not supported.&quot;
Case 2
strResult = &quot;The user does not have the necessary access.&quot;
Case 8
strResult = &quot;Interactive Process.&quot;
Case 9
strResult = &quot;The directory path to the service executable file cannot be found.&quot;
Case 21
strResult = &quot;Invalid parameters have been passed to the service.&quot;
Case 22
strResult = &quot;The account that this service runs under is invalid or lacks the permissions to run the service.&quot;
End Select
If ret > 0 Then
‘ create failed, write event log entry
App.LogEvent &quot;NTTaskCreate: Win32_ScheduledJob.Create Failed. :&quot; & strResult, vbLogEventTypeError
End If
Set objTask = Nothing

End Sub

Public Function NTTaskExists(strCmdLine As String) As Boolean
‘ this connects to the NT Task Scheduler via WMI to determine if the desired NT Scheduled Task Exists
Dim objTasks As Object
Dim objTask As Object

NTTaskExists = False
‘ now connect to NT Task Scheduler to determine if the script is scheduled
‘ create and schedule it if necessary
Set objTasks = GetObject(&quot;winmgmts:{impersonationLevel=impersonate}&quot.InstancesOf(&quot;Win32_ScheduledJob&quot
For Each objTask In objTasks
If UCase(objTask.Command) = UCase(strCmdLine) Then
NTTaskExists = True
Exit For
End If
Next

End Function

  • #20


Hi again,

Sorry to all those who wanted my help but I was tied up and didn’t have any time to spare. Well I have had about 3 to four request for help and updates so heres what I have done, I have added some features to the last program. It now includes adding of jobs, enum (listing) of jobs added and also deleting of jobs.

I will be uploading this code shortly in

If in the mean time you want a copy then feel free to mail me.

Regards

Neil Giddings

Status
Not open for further replies.

Similar threads

  • Home

  • Forums

  • Software

  • Programmers

  • Development Methodologies and Architecture

  • Win API (Microsoft)

  • This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.

W3C Working Draft 02 December 2014

This version:
http://www.w3.org/TR/2014/WD-task-scheduler-20141202/
Latest version:
http://www.w3.org/TR/task-scheduler/
Latest editor’s draft:
http://www.w3.org/2012/sysapps/web-alarms/
Previous version:
http://www.w3.org/TR/2013/WD-web-alarms-20130205/
Editors:
Mahesh Kulkarni, Samsung Electronics,
Co., Ltd
, mahesh.kk@samsung.com
Former Editors:
Christophe Dumez, representing Intel and Samsung Electronics (Until January 2013 and mid-August 2014, respectively)
Repository:
We are on Github.
File a bug.
Commit history.

Copyright © 2014 W3C® (MIT, ERCIM, Keio, Beihang), All Rights Reserved. W3C liability, trademark and document use rules apply.


Abstract

This specification defines an API to schedule a task at a
specified time. When the indicated time is reached, the
application that scheduled the task will be notified via
a functional event on a service worker. A task event will
be delivered to a service worker, regardless of whether
the application is active on user agent. Applications such
as an alarm clock or an auto-updater may utilize this API
to perform certain action at a specified time.

Status of This Document

This section describes the status of this document at the
time of its publication. Other documents may supersede this
document. A list of current W3C publications and the
latest revision of this technical report can be found in the
W3C technical reports
index at http://www.w3.org/TR/.

The short name for this API has been changed from web-alarms
to task-scheduler as a more accurate description of its scope.

This document defines a System Level API to provide access to
the device settings to either schedule a notification or to indicate
that an application is to be started at a specific time.

This document was published by the System Applications Working
Group as an updated Public Working Draft. This document is
intended to become a W3C Recommendation. If you
wish to make comments regarding this document, please send them
to public-sysapps@w3.org
(subscribe,
archives).
All feedback is welcome.

Publication as a Working Draft does not imply endorsement by
the W3C
Membership. This is a draft document and may be updated, replaced
or obsoleted by other documents at any time. It is inappropriate
to cite this document as other than work in progress.

This document was produced by a group operating under the
5
February 2004 W3C
Patent Policy. W3C maintains a public list of any patent disclosures made in
connection with the deliverables of the group; that page also
includes instructions for disclosing a patent. An individual who
has actual knowledge of a patent which the individual believes
contains
Essential Claim(s) must disclose the information in
accordance with
section 6 of the W3C Patent Policy.

This document is governed by the 14 October 2005 W3C Process Document.

Table of Contents

  1. 1
    Introduction
  2. 2
    Conformance
  3. 3
    Terminology
  4. 4
    Requirements
  5. 5
    Task Scheduler API

    1. 5.1
      Interface ServiceWorkerRegistration
    2. 5.2
      Interface TaskScheduler
    3. 5.3
      Interface ScheduledTask
  6. 6
    Events

    1. 6.1
      Event Handler
    2. 6.2
      The TaskEvent Interface
    3. 6.3
      Firing task event to service worker
  7. References
  8. Acknowledgments

1
Introduction

This section is non-normative.

Example use of the ScheduledTask API for adding, getting and removing and listening for the alarm clock use cases:

How to set an alarm 10 minutes from now?

    // https://example.com/serviceworker.js
    this.ontask = function(task) {
        alert(task.data.message);
        console.log("Task scheduled at: " + new Date(task.time));
        // From here on we can write the data to IndexedDB, send it to any open windows,
        // display a notification, etc.
    }

    // https://example.com/webapp.js
    function onTaskAdded(task) {
        console.log("Task successfully scheduled.");
    }

    function onError(error) {
        alert("Sorry, couldn't set the alarm: " + error);
    }

    navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
        serviceWorkerRegistration.taskScheduler.add(Date.now() + (10 * 60000), {
            message: "It's been 10 minutes, your soup is ready!"
        }).then(onTaskAdded, onError);
    });
        

How to get all the scheduled tasks whose time is in the future?

    navigator.serviceWorker.getRegistration().then(function(registration) {
        registration.taskScheduler.getPendingTasks().then(function(tasks) {
            alert("There are " + tasks.length + " tasks set.");
        }, function(error) {
            alert("An error occurred getting the scheduled tasks.");
        });
    }, function(error) {
        alert("An error occurred getting the scheduled tasks.");
    });
        

How to remove a scheduled task?

    navigator.serviceWorker.getRegistration().then(function(registration) {
        var request = registration.taskScheduler.remove(id).then(function() {
                alert("Task removed");
            }, function(error) {
                alert("Sorry, can't remove the task.");
            });
    }, function(error) {
        alert("An error occurred getting the scheduled tasks.");
    });
        

2
Conformance

This specification defines conformance criteria for a single product: the user agent that implements
the interfaces that it contains.

Implementations that use ECMAScript to implement the APIs defined in this specification MUST implement them in a manner
consistent with the ECMAScript Bindings defined in the
Web IDL specification [WEBIDL], as this specification uses that
specification and terminology.

3
Terminology

A JSON-serializable object is an object that when serialized or stringified conforms to the JSON Grammar as defined in
[ECMASCRIPT].

The EventHandler
interface represents a callback used for handling events as defined in [HTML5].

The Promise interface provides
asynchronous access to the result of an operation that is ongoing, has yet to start, or has completed, as defined in
[ECMASCRIPT6].

The concepts queue a task,
event handler
IDL attribute
and fire a
simple event
are defined in [HTML5].

The concepts event and
fire an event named eare defined in [DOM].

The terms event handler and
event handler event
types
are defined in [HTML5].

Service worker, service worker registration, ServiceWorker, ServiceWorkerRegistration,
ServiceWorkerGlobalScope, ExtendableEvent, and Handle Functional Event are defined in
[SERVICE-WORKERS].

4
Requirements

Below is a summary of requirements associated with this API:

  1. An application must only be able to access its own scheduled tasks.
  2. A scheduled task identifier must be unique within the application origin.
  3. A scheduled task must persist if the system is restarted.
  4. A scheduled task must actively wake the system if the scheduled time is reached while sleeping.
  5. A scheduled task that was missed (e.g. because the device was off or the clock jumped past it) should be fired as
    soon as possible.
  6. A scheduled task and its associated data must be removed when the application’s service worker registration is uninstalled.

5
Task Scheduler API

This section is non-normative.

The task scheduler supports the following features:

  • Web applications can schedule multiple tasks and get a returned ID for each of them.
  • Each ScheduledTask has a unique identifier that can be used to specify and remove the scheduled task.
  • Web applications can pass a JSON-serializable object to describe more details about each task setting.
  • When a scheduled time is reached, an task event is
    sent to the application.
  • ScheduledTask API actually does more than setTimeout() because it can actively wake the
    system from sleeping and scheduled task are not lost when closing the application or restarting the system.

5.1
Interface ServiceWorkerRegistration

The Service Worker specification defines a ServiceWorkerRegistration interface
[SERVICE-WORKERS], which this specification extends.

partial interface ServiceWorkerRegistration {
    readonly attribute TaskScheduler taskScheduler;
}

The taskScheduler attribute provides the developer access to a
TaskScheduler.

5.2
Interface TaskScheduler

The TaskScheduler interface exposes methods to get, set or remove scheduled tasks. ScheduledTasks are
application specific, so there is no way to see the tasks scheduled by other applications nor to modify them.
Developers should set an ontask event handler in the associated service worker to listen for the task event when scheduled tasks should be executed.

interface TaskScheduler {
    Promise getPendingTasks();
    Promise add(DOMTimeStamp time, optional any data);
    Promise remove(DOMString taskId);
};

When invoked, the getPendingTasks() method must run the following steps:

  1. Make a request to the system to retrieve the tasks that were registered by the current application and whose
    scheduled time is in the future.
  2. Let promise be a new Promise object and resolver its associated resolver.
  3. Return promise and run the remaining steps asynchronously.
  4. If an error occurs, run these substeps and then terminate these steps:
    1. Let error be a new DOMException exception whose name is the same as the error
      returned.
    2. Run resolver‘s internal reject algorithm with error as value.
  5. When the operation completes successfully, run these substeps:
    1. Let tasks be a new array containing the ScheduledTask objects that were retrieved.
    2. Run resolver‘s intenal fulfill algorithm with tasks as value.

When invoked, the add(time[, data]) method
must run the following steps:

  1. Make a request to the system to schedule a new task for the current application that will trigger at the given
    time (number of milliseconds since the epoch). If the time argument is in the past, the task
    will be executed as soon as possible, asynchronously. The system must associate the
    JSON-serializable data with the task if provided.
  2. Let promise be a new Promise object and resolver its associated resolver.
  3. Return promise and run the remaining steps asynchronously.
  4. If an error occurs, run these substeps and then terminate these steps:

    1. Let error be a new DOMException exception whose name is
      "QuotaExceededError" if the data argument exceeds an implementation-dependent size limit, or
      whose name is the same as the error returned otherwise.
    2. Run resolver‘s internal reject algorithm with error as value.
  5. When the operation completes successfully, run these substeps:

    1. Let task be a new ScheduledTask object.
    2. Set task‘s id attribute to the unique identifier returned by the system for the newly
      registered task.
    3. Set task‘s time attribute to the time argument.
    4. Set task‘s data attribute to the data argument, if provided.
    5. Run resolver‘s internal fulfill algorithm with task as value.

When invoked, the remove(taskId) method
must run the following steps:

  1. Make a request to the system to unregister the task with the given unique taskId identifier.
  2. Let promise be a new Promise object and resolver its associated resolver.
  3. Return promise and run the remaining steps asynchronously.
  4. If an error occurs, run these substeps and then terminate these steps:

    1. Let error be a new DOMException exception whose name is the same as the error
      returned.
    2. Run resolver‘s internal reject algorithm with error as value.
  5. When the operation completes successfully, run these substeps:

    1. Let removed be a boolean value.
    2. Set removed to true if the task was removed, and to false if there was no task
      with the given identifier.
    3. Run resolver‘s intenal fulfill algorithm with removed as
      value.

5.3
Interface ScheduledTask

The ScheduledTask interface captures the properties of a scheduled task.

interface ScheduledTask {
    readonly attribute DOMString id;
    readonly attribute DOMTimeStamp time;
    readonly attribute any data;
};

The id attribute returns an identifier for the given
ScheduledTask object that is unique within the origin. An implementation must maintain
this identifier when a ScheduledTask is added.

The time attribute is the time at which this task is scheduled to
fire, in milliseconds past the epoch (e.g. Date.now() + n). Due to performance, the task may be delayed past this time.

The data attribute optionally represents the JSON-serializable
data
associated with the task.

6
Events

The Service Worker specification defines a ServiceWorkerGlobalScope interface
[SERVICE-WORKERS], which this specification extends.

partial interface ServiceWorkerGlobalScope {
    attribute EventHandler ontask;
};

6.1
Event Handler

The following is the event handler (and its corresponding event handler event type) that must be supported as attribute by the ServiceWorkerGlobalScope object.

event handler event handler event type
ontask task

6.2
The TaskEvent Interface

The TaskEvent interface represents a scheduled task.

interface TaskEvent : ExtendableEvent {
    readonly attribute ScheduledTask task;
};

6.3
Firing task event to service worker

A task event is fired when a scheduled task should be
executed. The scheduled task is originated from the system and will wake up a service worker if it is not currently running.

When the scheduled task task went off by the system, the user agent must (unless otherwise specified) run these steps:

  1. Let callback be an algorithm that when invoked with a global, fires a service worker task event named task given task on global.
  2. Then run Handle Functional Event with task‘s service worker registration and callback.

To fire a service worker task event named e given task, fire an event named e with an event using the TaskEvent interface whose task attribute is initialized to a new ScheduledEvent object representing task.

References

Acknowledgments

We would like to thank Kan-Ru Chen, Mounir Lamouri, Gene Lian and Jonas Sicking for their work on the API design, as
well as the WebAPI/B2G teams at Mozilla [B2G-ALARM].

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как отключить автоматическую перезагрузку windows 7 в биосе
  • Windows 10 home update windows 10 pro
  • Как полностью отключить one drive в windows 11
  • Наушники на компьютере не воспроизводят звук на компьютере windows
  • Hackrf one driver windows