Click here to Skip to main content
15,887,175 members
Articles / Programming Languages / Visual Basic
Tip/Trick

How to create a task in Windows Task Scheduler

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
14 Jun 2013CPOL 73.3K   7   6
Source code to demonstrate the creation of a new task in Windows Task Scheduler.

Introduction

A brief example of how to create a simple task in Windows Task Scheduler using VB. NET

Background

Tested on Windows 8.

A question in the CodeProject Quick Answers area prompted me to create a test program that shows how to create a task in Task Scheduler.

Specifically, the behavior of the Hidden attribute was in question. I used this code to determine the cause of the issue. See the comments in the code below to learn about the issue with the Hidden attribute.

Using the code

Copy the source code and modify to your needs. If you need C#, use one of the free code translators to translate it for you.

Add a Reference to C:\WINDOWS\SYSTEM32\taskschd.dll or C:\WINDOWS\SYSWOW64\taskschd.dll which will create Interop.TaskScheduler.dll.

VB
Imports TaskScheduler

Public Sub CreateSchedule()
    Dim taskService As ITaskService = New TaskScheduler.TaskScheduler()

    ' Connect to the TaskService
    taskService.Connect()

    ' Create a new task definition and assign properties
    Dim taskDefinition As ITaskDefinition = taskService.NewTask(0)
    taskDefinition.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW
    taskDefinition.RegistrationInfo.Description = "Testing the creation of a scheduled task via VB .NET"
    taskDefinition.Principal.LogonType = _TASK_LOGON_TYPE.TASK_LOGON_GROUP
    taskDefinition.Settings.Hidden = False ' Set to True when running task should be hidden
    ' NOTE: When Hidden is true, it does not work if _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN 
    '       is used as parameter to RegisterTaskDefinition
    '
    '
    ' Add a trigger that will fire the task every other day
    Dim taskTrigger As IDailyTrigger = _
        DirectCast(taskDefinition.Triggers.Create _
            (_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY), IDailyTrigger)
    ' Set to start ten minutes from now
    taskTrigger.StartBoundary = _
        DateTime.Now.AddMinutes(10).ToString _
        ("yyyy-MM-ddThh:mm:ss" & _
        TimeZone.CurrentTimeZone.GetUtcOffset(Now).ToString.Substring(0, 6))
    ' Rerun the task every other day
    taskTrigger.DaysInterval = 2


    ' Create the Task action 
    Dim taskAction As IExecAction = _
        DirectCast(taskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC), IExecAction)
    ' The Path to the program
    taskAction.Path = "C:\windows\notepad.exe"
    ' Set Arguments
    taskAction.Arguments = ""
    taskAction.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)


    ' Register the task in the Task Scheduler's root folder
    Const taskName As String = "Testing creation of a scheduled task"
    Dim rootFolder As ITaskFolder = taskService.GetFolder("\")
    rootFolder.RegisterTaskDefinition( _
       taskName, taskDefinition, _
       CInt(_TASK_CREATION.TASK_CREATE_OR_UPDATE), _
       "MyUsername", "MyPassword", _
       _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD)

    ' Clean up the COM variables
    While System.Runtime.InteropServices.Marshal.ReleaseComObject(rootFolder) <> 0
        Application.DoEvents()
    End While
    rootFolder = Nothing
    While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskTrigger) <> 0
        Application.DoEvents()
    End While
    taskTrigger = Nothing
    While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskAction) <> 0
        Application.DoEvents()
    End While
    taskAction = Nothing
    While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskDefinition) <> 0
        Application.DoEvents()
    End While
    taskDefinition = Nothing
    While System.Runtime.InteropServices.Marshal.ReleaseComObject(taskService) <> 0
        Application.DoEvents()
    End While
    taskService = Nothing
    GC.Collect() ' Start .NET CLR Garbage Collection
    GC.WaitForPendingFinalizers() ' Wait for Garbage Collection to finish
End Sub

History

  • Version 1 - 14 June 2013.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Retired
United States United States
I’m retired. When I started my career, programming projects consisted of plugging wires into plug boards to create punch card processing applications to be run on electrical accounting machine like the IBM 402, 407, 085, 088, 514, 519, etc. From there, I moved to writing SPS and Autocoder applications on an IBM 1401 with 4K of memory eventually upgraded to 16K of memory. After many years of migrating my skills to various languages on various hardware platforms, I became an Information Technology Director where I didn’t need to program anymore. So, starting in 1996, I volunteered my time with a local community cable television organization and built some applications to help them run their operations. Originally in Clipper Summer 1987 and later Clipper 5.2, I migrated and enhanced those applications to VB .NET 2003 in 2003. I retired from my full-time job in 2010. Since then, I have continued to support the local community cable tv organization's applications. In 2013, I migrated the VB .NET 2003 Solution to VB .NET 2012 so that it can run on 64-bit computers and interact with Microsoft Office 2010. The upgrade went smoothly. In mid 2013, I developed a VB .NET 2012 application for them to download election results data from the Secretary of State's web site, format the results and send them to a VizRT character generator for on-air display.

Comments and Discussions

 
QuestionCreate task under current user without giving password Pin
Dmitry Post28-Jul-14 17:29
Dmitry Post28-Jul-14 17:29 
AnswerRe: Create task under current user without giving password Pin
Mike Meinz29-Jul-14 2:31
Mike Meinz29-Jul-14 2:31 
GeneralRe: Create task under current user without giving password Pin
Dmitry Post5-Aug-14 12:43
Dmitry Post5-Aug-14 12:43 
GeneralRe: Create task under current user without giving password Pin
Mike Meinz5-Aug-14 13:21
Mike Meinz5-Aug-14 13:21 
GeneralMy vote of 5 Pin
maticot24-Jun-13 9:13
maticot24-Jun-13 9:13 
GeneralRe: My vote of 5 Pin
Mike Meinz24-Jun-13 9:19
Mike Meinz24-Jun-13 9:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.