taskmaster

package module
v0.0.0-...-e9fb150 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 6, 2023 License: MIT Imports: 12 Imported by: 0

README

Build status Go Report Card PkgGoDev

taskmaster

Windows Task Scheduler Library for Go

NOTE: the API is not stable, I reserve the right to change it before v1.0. Task Scheduler is complex, and it is difficult to create a sane, useable interface for it. I would highly encourage you to make use of Go modules and pin a specific commit.

taskmaster villain

What is taskmaster?

Taskmaster is a library for managing Scheduled Tasks in Windows. It allows you to easily create, modify, delete, execute, kill, and view scheduled tasks, on your local machine or on a remote one. It provides much more speed and power than using the native Task Scheduler GUI in Windows, and the Scheduled Task Powershell cmdlets.

Because taskmaster interfaces directly with Task Scheduler COM objects, it allows you to do things you can't do with the Task Scheduler GUI or Powershell cmdlets. COM handler task actions can be viewed, manipulated, and created, more settings can be used when creating or modifying scheduled tasks, etc. Taskmaster exposes the full potential of Windows Scheduled Tasks in a clean, simple interface.

Documentation

As I was researching the Task Scheduler COM interface more and more, I quickly realized just how complex and confusing all the different parts of Task Scheduler are. So I set out to concisely copy the documentation from MSDN into taskmaster, but also consolidate it and add information that is buried in the depths of MSDN. This should make using both taskmaster and the existing Task Scheduler tools easier, having a ton of information and links to Task Scheduler internals available via GoDocs. If you find info that I missed, feel free to submit an issue or better yet open a PR :)

There are a lot of hidden gotchas and quirks within Task Scheduler, so I would highly recommend perusing the official docs before attempting really anything with this library on MSDN.

Documentation

Rendered for windows/amd64

Index

Constants

View Source
const S_FALSE = 0x00000001

S_FALSE is returned by CoInitialize if it was already called on this thread.

Variables

View Source
var (
	ErrTargetUnsupported    = errors.New("error connecting to the Task Scheduler service: cannot connect to the XP or server 2003 computer")
	ErrConnectionFailure    = errors.New("error connecting to the Task Scheduler service: cannot connect to target computer")
	ErrInvalidPath          = errors.New(`path must start with root folder "\"`)
	ErrNoActions            = errors.New("definition must have at least one action")
	ErrInvalidPrinciple     = errors.New("both UserId and GroupId are defined for the principal; they are mutually exclusive")
	ErrRunningTaskCompleted = errors.New("the running task completed while it was getting parsed")
)

Functions

func PeriodToString

func PeriodToString(p period.Period) string

func StringToPeriod

func StringToPeriod(s string) (period.Period, error)

func TaskDateToTime

func TaskDateToTime(s string) (time.Time, error)

func TimeToTaskDate

func TimeToTaskDate(t time.Time) string

Types

type Action

type Action interface {
	GetID() string
	GetType() TaskActionType
}

type BootTrigger

type BootTrigger struct {
	TaskTrigger
	Delay period.Period // indicates the amount of time between when the system is booted and when the task is started
}

BootTrigger triggers the task when the computer boots. Only Administrators can create tasks with a BootTrigger. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iboottrigger

func (BootTrigger) GetType

func (BootTrigger) GetType() TaskTriggerType

type ComHandlerAction

type ComHandlerAction struct {
	ID      string
	ClassID string
	Data    string
}

ComHandlerAction is an action that fires a COM handler. Can only be used if TASK_COMPATIBILITY_V2 or above is set. The clisd parameter is the CLSID of the COM object that will get instantiated when the action executes, and the data parameter is the arguments passed to the COM object. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-icomhandleraction

func (ComHandlerAction) GetID

func (c ComHandlerAction) GetID() string

func (ComHandlerAction) GetType

func (ComHandlerAction) GetType() TaskActionType

type CustomTrigger

type CustomTrigger struct {
	TaskTrigger
}

func (CustomTrigger) GetType

func (CustomTrigger) GetType() TaskTriggerType

type DailyTrigger

type DailyTrigger struct {
	TaskTrigger
	DayInterval DayInterval   // the interval between the days in the schedule
	RandomDelay period.Period // a delay time that is randomly added to the start time of the trigger
}

DailyTrigger triggers the task on a daily schedule. For example, the task starts at a specific time every day, every other day, or every third day. The time of day that the task is started is set by StartBoundary, which must be set. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-idailytrigger

func (DailyTrigger) GetType

func (DailyTrigger) GetType() TaskTriggerType

type DayInterval

type DayInterval uint8

DayInterval specifies if a task runs every day or every other day.

const (
	EveryDay      DayInterval = 1
	EveryOtherDay DayInterval = 2
)

func (DayInterval) String

func (d DayInterval) String() string

type DayOfMonth

type DayOfMonth uint32

DayOfMonth is a day of a month.

const (
	One DayOfMonth = 1 << iota
	Two
	Three
	Four
	Five
	Six
	Seven
	Eight
	Nine
	Ten
	Eleven
	Twelve
	Thirteen
	Fourteen
	Fifteen
	Sixteen
	Seventeen
	Eighteen
	Nineteen
	Twenty
	TwentyOne
	TwentyTwo
	TwentyThree
	TwentyFour
	TwentyFive
	TwentySix
	TwentySeven
	TwentyEight
	TwentyNine
	Thirty
	ThirtyOne
	LastDayOfMonth
	AllDaysOfMonth DayOfMonth = (1 << 31) - 1
)

func IntToDayOfMonth

func IntToDayOfMonth(dayOfMonth int) (DayOfMonth, error)

func (DayOfMonth) String

func (d DayOfMonth) String() string

type DayOfWeek

type DayOfWeek uint16

DayOfWeek is a day of the week.

const (
	Sunday DayOfWeek = 1 << iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Saturday
	AllDays DayOfWeek = (1 << 7) - 1
)

func (DayOfWeek) String

func (d DayOfWeek) String() string

type Definition

type Definition struct {
	Actions          []Action
	Context          string // specifies the security context under which the actions of the task are performed
	Data             string // the data that is associated with the task
	Principal        Principal
	RegistrationInfo RegistrationInfo
	Settings         TaskSettings
	Triggers         []Trigger
	XMLText          string // the XML-formatted definition of the task
}

Definition defines all the components of a task, such as the task settings, triggers, actions, and registration information https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-itaskdefinition

func (*Definition) AddAction

func (d *Definition) AddAction(action Action)

func (*Definition) AddTrigger

func (d *Definition) AddTrigger(trigger Trigger)

type EventTrigger

type EventTrigger struct {
	TaskTrigger
	Delay        period.Period     // indicates the amount of time between when the event occurs and when the task is started
	Subscription string            // a query string that identifies the event that fires the trigger
	ValueQueries map[string]string // a collection of named XPath queries. Each query in the collection is applied to the last matching event XML returned from the subscription query
}

EventTrigger triggers the task when a specific event occurs. A maximum of 500 tasks with event subscriptions can be created. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-ieventtrigger

func (EventTrigger) GetType

func (EventTrigger) GetType() TaskTriggerType

type ExecAction

type ExecAction struct {
	ID         string
	Path       string
	Args       string
	WorkingDir string
}

ExecAction is an action that performs a command-line operation. The args field can have up to 32 $(ArgX) values, such as '/c $(Arg0) $(Arg1)'. This will allow the arguments to be dynamically entered when the task is run. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iexecaction

func (ExecAction) GetID

func (e ExecAction) GetID() string

func (ExecAction) GetType

func (ExecAction) GetType() TaskActionType

type IdleSettings

type IdleSettings struct {
	IdleDuration  period.Period // the amount of time that the computer must be in an idle state before the task is run
	RestartOnIdle bool          // whether the task is restarted when the computer cycles into an idle condition more than once
	StopOnIdleEnd bool          // indicates that the Task Scheduler will terminate the task if the idle condition ends before the task is completed
	WaitTimeout   period.Period // the amount of time that the Task Scheduler will wait for an idle condition to occur
}

IdleSettings specifies how the Task Scheduler performs tasks when the computer is in an idle condition. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iidlesettings

type IdleTrigger

type IdleTrigger struct {
	TaskTrigger
}

IdleTrigger triggers the task when the computer goes into an idle state. An IdleTrigger will only trigger a task action if the computer goes into an idle state after the start boundary of the trigger https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iidletrigger

func (IdleTrigger) GetType

func (IdleTrigger) GetType() TaskTriggerType

type LogonTrigger

type LogonTrigger struct {
	TaskTrigger
	Delay  period.Period // indicates the amount of time between when the user logs on and when the task is started
	UserID string        // the identifier of the user. If left empty, the trigger will fire when any user logs on
}

LogonTrigger triggers the task when a specific user logs on. When the Task Scheduler service starts, all logged-on users are enumerated and any tasks registered with logon triggers that match the logged on user are run. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-ilogontrigger

func (LogonTrigger) GetType

func (LogonTrigger) GetType() TaskTriggerType

type Month

type Month uint16

Month is one of the 12 months.

const (
	January Month = 1 << iota
	February
	March
	April
	May
	June
	July
	August
	September
	October
	November
	December
	AllMonths Month = (1 << 12) - 1
)

func (Month) String

func (m Month) String() string

type MonthlyDOWTrigger

type MonthlyDOWTrigger struct {
	TaskTrigger
	DaysOfWeek           DayOfWeek     // the days of the week during which the task runs
	MonthsOfYear         Month         // the months of the year during which the task runs
	RandomDelay          period.Period // a delay time that is randomly added to the start time of the trigger
	RunOnLastWeekOfMonth bool          // indicates that the task runs on the last week of the month
	WeeksOfMonth         Week          // the weeks of the month during which the task runs
}

MonthlyDOWTrigger triggers the task on a monthly day-of-week schedule. For example, the task starts on a specific days of the week, weeks of the month, and months of the year. The time of day that the task is started is set by StartBoundary, which must be set. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-imonthlydowtrigger

func (MonthlyDOWTrigger) GetType

type MonthlyTrigger

type MonthlyTrigger struct {
	TaskTrigger
	DaysOfMonth          DayOfMonth    // the days of the month during which the task runs
	MonthsOfYear         Month         // the months of the year during which the task runs
	RandomDelay          period.Period // a delay time that is randomly added to the start time of the trigger
	RunOnLastWeekOfMonth bool          // indicates that the task runs on the last week of the month
}

MonthlyTrigger triggers the task on a monthly schedule. For example, the task starts on specific days of specific months. The time of day that the task is started is set by StartBoundary, which must be set. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-imonthlytrigger

func (MonthlyTrigger) GetType

func (MonthlyTrigger) GetType() TaskTriggerType

type NetworkSettings

type NetworkSettings struct {
	ID   string // a GUID value that identifies a network profile
	Name string // the name of a network profile
}

NetworkSettings provides the settings that the Task Scheduler service uses to obtain a network profile. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-inetworksettings

type Principal

type Principal struct {
	Name      string        // the name of the principal
	GroupID   string        // the identifier of the user group that is required to run the tasks
	ID        string        // the identifier of the principal
	LogonType TaskLogonType // the security logon method that is required to run the tasks
	RunLevel  TaskRunLevel  // the identifier that is used to specify the privilege level that is required to run the tasks
	UserID    string        // the user identifier that is required to run the tasks
}

Principal provides security credentials that define the security context for the tasks that are associated with it. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iprincipal

type RegisteredTask

type RegisteredTask struct {
	Name           string // the name of the registered task
	Path           string // the path to where the registered task is stored
	Definition     Definition
	Enabled        bool
	State          TaskState  // the operational state of the registered task
	MissedRuns     uint       // the number of times the registered task has missed a scheduled run
	NextRunTime    time.Time  // the time when the registered task is next scheduled to run
	LastRunTime    time.Time  // the time the registered task was last run
	LastTaskResult TaskResult // the results that were returned the last time the registered task was run
	// contains filtered or unexported fields
}

RegisteredTask is a task that is registered in the Task Scheduler database. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iregisteredtask

func (*RegisteredTask) GetInstances

func (r *RegisteredTask) GetInstances() (RunningTaskCollection, error)

GetInstances returns all of the currently running instances of a registered task. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nf-taskschd-iregisteredtask-getinstances

func (*RegisteredTask) Release

func (r *RegisteredTask) Release()

Release frees the registered task COM object. Must be called before program termination to avoid memory leaks.

func (*RegisteredTask) Run

func (r *RegisteredTask) Run(args ...string) (RunningTask, error)

Run starts an instance of a registered task. If the task was started successfully, a pointer to a running task will be returned. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nf-taskschd-iregisteredtask-run

func (*RegisteredTask) RunEx

func (r *RegisteredTask) RunEx(args []string, flags TaskRunFlags, sessionID int, user string) (RunningTask, error)

RunEx starts an instance of a registered task. If the task was started successfully, a pointer to a running task will be returned. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nf-taskschd-iregisteredtask-runex

func (*RegisteredTask) Stop

func (r *RegisteredTask) Stop() error

Stop kills all running instances of the registered task that the current user has access to. If all instances were killed, Stop returns true, otherwise Stop returns false. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nf-taskschd-iregisteredtask-stop

type RegisteredTaskCollection

type RegisteredTaskCollection []RegisteredTask

RegisteredTaskCollection is a collection of registered tasks.

func (RegisteredTaskCollection) Release

func (r RegisteredTaskCollection) Release()

Release frees all the registered task COM objects in the collection. Must be called before program termination to avoid memory leaks.

type RegistrationInfo

type RegistrationInfo struct {
	Author             string
	Date               time.Time
	Description        string
	Documentation      string
	SecurityDescriptor string
	Source             string
	URI                string
	Version            string
}

RegistrationInfo provides the administrative information that can be used to describe the task https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iregistrationinfo

type RegistrationTrigger

type RegistrationTrigger struct {
	TaskTrigger
	Delay period.Period // the amount of time between when the task is registered and when the task is started
}

RegistrationTrigger triggers the task when the task is registered. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iregistrationtrigger

func (RegistrationTrigger) GetType

type RepetitionPattern

type RepetitionPattern struct {
	RepetitionDuration period.Period // how long the pattern is repeated
	RepetitionInterval period.Period // the amount of time between each restart of the task. Required if RepetitionDuration is specified. Minimum time is one minute
	StopAtDurationEnd  bool          // indicates if a running instance of the task is stopped at the end of the repetition pattern duration
}

RepetitionPattern defines how often the task is run and how long the repetition pattern is repeated after the task is started. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-irepetitionpattern

type RunningTask

type RunningTask struct {
	CurrentAction string    // the name of the current action that the running task is performing
	EnginePID     uint      // the process ID for the engine (process) which is running the task
	InstanceGUID  string    // the GUID identifier for this instance of the task
	Name          string    // the name of the task
	Path          string    // the path to where the task is stored
	State         TaskState // an identifier for the state of the running task
	// contains filtered or unexported fields
}

RunningTask is a task that is currently running. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-irunningtask

func (RunningTask) Refresh

func (r RunningTask) Refresh() error

Refresh refreshes all of the local instance variables of the running task. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nf-taskschd-irunningtask-refresh

func (*RunningTask) Release

func (r *RunningTask) Release()

Release frees the running task COM object. Must be called before program termination to avoid memory leaks.

func (*RunningTask) Stop

func (r *RunningTask) Stop() error

Stop kills and releases a running task. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nf-taskschd-irunningtask-stop

type RunningTaskCollection

type RunningTaskCollection []RunningTask

RunningTaskCollection is a collection of running tasks.

func (RunningTaskCollection) Release

func (r RunningTaskCollection) Release()

Release frees all the running task COM objects in the collection. Must be called before program termination to avoid memory leaks.

func (RunningTaskCollection) Stop

func (r RunningTaskCollection) Stop() error

Stop kills and frees all the running tasks COM objects in the collection. If an error is encountered while stopping a running task, Stop returns the error without attempting to stop any other running tasks in the collection.

type SessionStateChangeTrigger

type SessionStateChangeTrigger struct {
	TaskTrigger
	Delay       period.Period              // indicates how long of a delay takes place before a task is started after a Terminal Server session state change is detected
	StateChange TaskSessionStateChangeType // the kind of Terminal Server session change that would trigger a task launch
	UserId      string                     // the user for the Terminal Server session. When a session state change is detected for this user, a task is started
}

SessionStateChangeTrigger triggers the task when a specific user session state changes. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-isessionstatechangetrigger

func (SessionStateChangeTrigger) GetType

type TaskActionType

type TaskActionType uint

TaskActionType specifies the type of a task action. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_action_type

const (
	TASK_ACTION_EXEC         TaskActionType = 0
	TASK_ACTION_COM_HANDLER  TaskActionType = 5
	TASK_ACTION_SEND_EMAIL   TaskActionType = 6
	TASK_ACTION_SHOW_MESSAGE TaskActionType = 7
)

func (TaskActionType) String

func (t TaskActionType) String() string

type TaskCompatibility

type TaskCompatibility uint

TaskCompatibility specifies the compatibility of a registered task. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_compatibility

const (
	TASK_COMPATIBILITY_AT TaskCompatibility = iota
	TASK_COMPATIBILITY_V1
	TASK_COMPATIBILITY_V2
	TASK_COMPATIBILITY_V2_1
	TASK_COMPATIBILITY_V2_2
	TASK_COMPATIBILITY_V2_3
	TASK_COMPATIBILITY_V2_4
)

func (TaskCompatibility) String

func (c TaskCompatibility) String() string

type TaskCreationFlags

type TaskCreationFlags uint

TaskCreationFlags specifies how a task will be created. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_creation

const (
	TASK_VALIDATE_ONLY                TaskCreationFlags = 0x01
	TASK_CREATE                       TaskCreationFlags = 0x02
	TASK_UPDATE                       TaskCreationFlags = 0x04
	TASK_CREATE_OR_UPDATE             TaskCreationFlags = 0x06
	TASK_DISABLE                      TaskCreationFlags = 0x08
	TASK_DONT_ADD_PRINCIPAL_ACE       TaskCreationFlags = 0x10
	TASK_IGNORE_REGISTRATION_TRIGGERS TaskCreationFlags = 0x20
)

type TaskEnumFlags

type TaskEnumFlags uint

TaskEnumFlags specifies how tasks will be enumerated. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_enum_flags

const (
	TASK_ENUM_HIDDEN TaskEnumFlags = 1 // enumerate all tasks, including tasks that are hidden
)

type TaskFolder

type TaskFolder struct {
	Name            string
	Path            string
	SubFolders      []*TaskFolder
	RegisteredTasks RegisteredTaskCollection
	// contains filtered or unexported fields
}

func (*TaskFolder) Release

func (f *TaskFolder) Release()

Release frees all the registered task COM objects in the folder and all subfolders. Must be called before program termination to avoid memory leaks.

type TaskInstancesPolicy

type TaskInstancesPolicy uint

TaskInstancesPolicy specifies what the Task Scheduler service will do when multiple instances of a task are triggered or operating at once. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_instances_policy

const (
	TASK_INSTANCES_PARALLEL      TaskInstancesPolicy = iota // start new instance while an existing instance is running
	TASK_INSTANCES_QUEUE                                    // start a new instance of the task after all other instances of the task are complete
	TASK_INSTANCES_IGNORE_NEW                               // do not start a new instance if an existing instance of the task is running
	TASK_INSTANCES_STOP_EXISTING                            // stop an existing instance of the task before it starts a new instance
)

func (TaskInstancesPolicy) String

func (t TaskInstancesPolicy) String() string

type TaskLogonType

type TaskLogonType uint

TaskLogonType specifies how a registered task will authenticate when it executes. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_logon_type

const (
	TASK_LOGON_NONE                          TaskLogonType = iota // the logon method is not specified. Used for non-NT credentials
	TASK_LOGON_PASSWORD                                           // use a password for logging on the user. The password must be supplied at registration time
	TASK_LOGON_S4U                                                // the service will log the user on using Service For User (S4U), and the task will run in a non-interactive desktop. When an S4U logon is used, no password is stored by the system and there is no access to either the network or to encrypted files
	TASK_LOGON_INTERACTIVE_TOKEN                                  // user must already be logged on. The task will be run only in an existing interactive session
	TASK_LOGON_GROUP                                              // group activation
	TASK_LOGON_SERVICE_ACCOUNT                                    // indicates that a Local System, Local Service, or Network Service account is being used as a security context to run the task
	TASK_LOGON_INTERACTIVE_TOKEN_OR_PASSWORD                      // first use the interactive token. If the user is not logged on (no interactive token is available), then the password is used. The password must be specified when a task is registered. This flag is not recommended for new tasks because it is less reliable than TASK_LOGON_PASSWORD
)

func (TaskLogonType) String

func (t TaskLogonType) String() string

type TaskResult

type TaskResult uint32
const (
	SCHED_S_SUCCESS    TaskResult = 0x0
	SCHED_S_TASK_READY TaskResult = iota + 0x00041300
	SCHED_S_TASK_RUNNING
	SCHED_S_TASK_DISABLED
	SCHED_S_TASK_HAS_NOT_RUN
	SCHED_S_TASK_NO_MORE_RUNS
	SCHED_S_TASK_NOT_SCHEDULED
	SCHED_S_TASK_TERMINATED
	SCHED_S_TASK_NO_VALID_TRIGGERS
	SCHED_S_EVENT_TRIGGER
	SCHED_S_SOME_TRIGGERS_FAILED TaskResult = 0x0004131B
	SCHED_S_BATCH_LOGON_PROBLEM  TaskResult = 0x0004131C
	SCHED_S_TASK_QUEUED          TaskResult = 0x00041325
)

func (TaskResult) String

func (r TaskResult) String() string

type TaskRunFlags

type TaskRunFlags uint

TaskRunFlags specifies how a task will be executed. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_run_flags

const (
	TASK_RUN_NO_FLAGS           TaskRunFlags = iota // the task is run with all flags ignored
	TASK_RUN_AS_SELF                                // the task is run as the user who is calling the Run method
	TASK_RUN_IGNORE_CONSTRAINTS                     // the task is run regardless of constraints such as "do not run on batteries" or "run only if idle"
	TASK_RUN_USE_SESSION_ID                         // the task is run using a terminal server session identifier
	TASK_RUN_USER_SID                               // the task is run using a security identifier
)

type TaskRunLevel

type TaskRunLevel uint

TaskRunLevel specifies whether the task will be run with full permissions or not. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_runlevel_type

const (
	TASK_RUNLEVEL_LUA     TaskRunLevel = iota // task will be run with the least privileges
	TASK_RUNLEVEL_HIGHEST                     // task will be run with the highest privileges
)

func (TaskRunLevel) String

func (t TaskRunLevel) String() string

type TaskService

type TaskService struct {
	// contains filtered or unexported fields
}

func Connect

func Connect() (TaskService, error)

Connect connects to the local Task Scheduler service, using the current token for authentication. This function must run before any other functions in taskmaster can be used.

func ConnectWithOptions

func ConnectWithOptions(serverName, domain, username, password string) (TaskService, error)

ConnectWithOptions connects to a local or remote Task Scheduler service. This function must run before any other functions in taskmaster can be used. If the serverName parameter is empty, a connection to the local Task Scheduler service will be attempted. If the user and password parameters are empty, the current token will be used for authentication.

func (*TaskService) CreateTask

func (t *TaskService) CreateTask(path string, newTaskDef Definition, overwrite bool) (RegisteredTask, bool, error)

CreateTask creates a registered task on the connected computer. CreateTask returns true if the task was successfully registered, and false if the overwrite parameter is false and a task at the specified path already exists.

func (*TaskService) CreateTaskEx

func (t *TaskService) CreateTaskEx(path string, newTaskDef Definition, username, password string, logonType TaskLogonType, overwrite bool) (RegisteredTask, bool, error)

CreateTaskEx creates a registered task on the connected computer. CreateTaskEx returns true if the task was successfully registered, and false if the overwrite parameter is false and a task at the specified path already exists.

func (*TaskService) DeleteFolder

func (t *TaskService) DeleteFolder(path string, deleteRecursively bool) (bool, error)

DeleteFolder removes a task folder from the connected computer. If the deleteRecursively parameter is set to true, all tasks and subfolders will be removed recursively. If it's set to false, DeleteFolder will return true if the folder was empty and deleted successfully, and false otherwise.

func (*TaskService) DeleteTask

func (t *TaskService) DeleteTask(path string) error

DeleteTask removes a registered task from the connected computer.

func (*TaskService) Disconnect

func (t *TaskService) Disconnect()

Disconnect frees all the Task Scheduler COM objects that have been created. If this function is not called before the parent program terminates, memory leaks will occur.

func (TaskService) GetConnectedComputerName

func (t TaskService) GetConnectedComputerName() string

func (TaskService) GetConnectedDomain

func (t TaskService) GetConnectedDomain() string

func (TaskService) GetConnectedUser

func (t TaskService) GetConnectedUser() string

func (*TaskService) GetRegisteredTask

func (t *TaskService) GetRegisteredTask(path string) (RegisteredTask, error)

GetRegisteredTask attempts to find the specified registered task and returns a pointer to it if it exists. If it doesn't exist, nil will be returned in place of the registered task.

func (*TaskService) GetRegisteredTasks

func (t *TaskService) GetRegisteredTasks() (RegisteredTaskCollection, error)

GetRegisteredTasks enumerates the Task Scheduler database for all currently registered tasks.

func (*TaskService) GetRunningTasks

func (t *TaskService) GetRunningTasks() (RunningTaskCollection, error)

GetRunningTasks enumerates the Task Scheduler database for all currently running tasks.

func (TaskService) GetTaskFolder

func (t TaskService) GetTaskFolder(path string) (TaskFolder, error)

GetTaskFolder enumerates the Task Schedule database for all task sub folders and currently registered tasks under the folder specified, if it exists. If it doesn't exist, nil will be returned in place of the task folder.

func (TaskService) GetTaskFolders

func (t TaskService) GetTaskFolders() (TaskFolder, error)

GetTaskFolders enumerates the Task Schedule database for all task folders and currently registered tasks.

func (TaskService) IsConnected

func (t TaskService) IsConnected() bool

func (TaskService) NewTaskDefinition

func (t TaskService) NewTaskDefinition() Definition

NewTaskDefinition returns a new task definition that can be used to register a new task. Task settings and properties are set to Task Scheduler default values.

func (*TaskService) UpdateTask

func (t *TaskService) UpdateTask(path string, newTaskDef Definition) (RegisteredTask, error)

UpdateTask updates a registered task.

func (*TaskService) UpdateTaskEx

func (t *TaskService) UpdateTaskEx(path string, newTaskDef Definition, username, password string, logonType TaskLogonType) (RegisteredTask, error)

UpdateTaskEx updates a registered task.

type TaskSessionStateChangeType

type TaskSessionStateChangeType uint

TaskSessionStateChangeType specifies the type of session state change that a SessionStateChange trigger will trigger on. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_session_state_change_type

const (
	TASK_CONSOLE_CONNECT    TaskSessionStateChangeType = 1 // Terminal Server console connection state change. For example, when you connect to a user session on the local computer by switching users on the computer
	TASK_CONSOLE_DISCONNECT TaskSessionStateChangeType = 2 // Terminal Server console disconnection state change. For example, when you disconnect to a user session on the local computer by switching users on the computer
	TASK_REMOTE_CONNECT     TaskSessionStateChangeType = 3 // Terminal Server remote connection state change. For example, when a user connects to a user session by using the Remote Desktop Connection program from a remote computer
	TASK_REMOTE_DISCONNECT  TaskSessionStateChangeType = 4 // Terminal Server remote disconnection state change. For example, when a user disconnects from a user session while using the Remote Desktop Connection program from a remote computer
	TASK_SESSION_LOCK       TaskSessionStateChangeType = 7 // Terminal Server session locked state change. For example, this state change causes the task to run when the computer is locked
	TASK_SESSION_UNLOCK     TaskSessionStateChangeType = 8 // Terminal Server session unlocked state change. For example, this state change causes the task to run when the computer is unlocked
)

func (TaskSessionStateChangeType) String

type TaskSettings

type TaskSettings struct {
	AllowDemandStart       bool              // indicates that the task can be started by using either the Run command or the Context menu
	AllowHardTerminate     bool              // indicates that the task may be terminated by the Task Scheduler service using TerminateProcess
	Compatibility          TaskCompatibility // indicates which version of Task Scheduler a task is compatible with
	DeleteExpiredTaskAfter string            // the amount of time that the Task Scheduler will wait before deleting the task after it expires
	DontStartOnBatteries   bool              // indicates that the task will not be started if the computer is running on batteries
	Enabled                bool              // indicates that the task is enabled
	TimeLimit              period.Period     // the amount of time that is allowed to complete the task
	Hidden                 bool              // indicates that the task will not be visible in the UI
	IdleSettings
	MultipleInstances TaskInstancesPolicy // defines how the Task Scheduler deals with multiple instances of the task
	NetworkSettings
	Priority                  uint          // the priority level of the task, ranging from 0 - 10, where 0 is the highest priority, and 10 is the lowest. Only applies to ComHandler, Email, and MessageBox actions
	RestartCount              uint          // the number of times that the Task Scheduler will attempt to restart the task
	RestartInterval           period.Period // specifies how long the Task Scheduler will attempt to restart the task
	RunOnlyIfIdle             bool          // indicates that the Task Scheduler will run the task only if the computer is in an idle condition
	RunOnlyIfNetworkAvailable bool          // indicates that the Task Scheduler will run the task only when a network is available
	StartWhenAvailable        bool          // indicates that the Task Scheduler can start the task at any time after its scheduled time has passed
	StopIfGoingOnBatteries    bool          // indicates that the task will be stopped if the computer is going onto batteries
	WakeToRun                 bool          // indicates that the Task Scheduler will wake the computer when it is time to run the task, and keep the computer awake until the task is completed
}

TaskSettings provides the settings that the Task Scheduler service uses to perform the task https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-itasksettings

type TaskState

type TaskState uint

TaskState specifies the state of a running or registered task. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_state

const (
	TASK_STATE_UNKNOWN  TaskState = iota // the state of the task is unknown
	TASK_STATE_DISABLED                  // the task is registered but is disabled and no instances of the task are queued or running. The task cannot be run until it is enabled
	TASK_STATE_QUEUED                    // instances of the task are queued
	TASK_STATE_READY                     // the task is ready to be executed, but no instances are queued or running
	TASK_STATE_RUNNING                   // one or more instances of the task is running
)

func (TaskState) String

func (t TaskState) String() string

type TaskTrigger

type TaskTrigger struct {
	Enabled            bool          // indicates whether the trigger is enabled
	EndBoundary        time.Time     // the date and time when the trigger is deactivated
	ExecutionTimeLimit period.Period // the maximum amount of time that the task launched by this trigger is allowed to run
	ID                 string        // the identifier for the trigger
	RepetitionPattern
	StartBoundary time.Time // the date and time when the trigger is activated
}

TaskTrigger provides the common properties that are inherited by all trigger objects. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-itrigger

func (TaskTrigger) GetEnabled

func (t TaskTrigger) GetEnabled() bool

func (TaskTrigger) GetEndBoundary

func (t TaskTrigger) GetEndBoundary() time.Time

func (TaskTrigger) GetExecutionTimeLimit

func (t TaskTrigger) GetExecutionTimeLimit() period.Period

func (TaskTrigger) GetID

func (t TaskTrigger) GetID() string

func (TaskTrigger) GetRepetitionDuration

func (t TaskTrigger) GetRepetitionDuration() period.Period

func (TaskTrigger) GetRepetitionInterval

func (t TaskTrigger) GetRepetitionInterval() period.Period

func (TaskTrigger) GetStartBoundary

func (t TaskTrigger) GetStartBoundary() time.Time

func (TaskTrigger) GetStopAtDurationEnd

func (t TaskTrigger) GetStopAtDurationEnd() bool

type TaskTriggerType

type TaskTriggerType uint

TaskTriggerType specifies the type of a task trigger. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/ne-taskschd-task_trigger_type2

const (
	TASK_TRIGGER_EVENT                TaskTriggerType = 0
	TASK_TRIGGER_TIME                 TaskTriggerType = 1
	TASK_TRIGGER_DAILY                TaskTriggerType = 2
	TASK_TRIGGER_WEEKLY               TaskTriggerType = 3
	TASK_TRIGGER_MONTHLY              TaskTriggerType = 4
	TASK_TRIGGER_MONTHLYDOW           TaskTriggerType = 5
	TASK_TRIGGER_IDLE                 TaskTriggerType = 6
	TASK_TRIGGER_REGISTRATION         TaskTriggerType = 7
	TASK_TRIGGER_BOOT                 TaskTriggerType = 8
	TASK_TRIGGER_LOGON                TaskTriggerType = 9
	TASK_TRIGGER_SESSION_STATE_CHANGE TaskTriggerType = 11
	TASK_TRIGGER_CUSTOM_TRIGGER_01    TaskTriggerType = 12
)

func (TaskTriggerType) String

func (t TaskTriggerType) String() string

type TimeTrigger

type TimeTrigger struct {
	TaskTrigger
	RandomDelay period.Period // a delay time that is randomly added to the start time of the trigger
}

TimeTrigger triggers the task at a specific time of day. StartBoundary determines when the trigger fires. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-itimetrigger

func (TimeTrigger) GetType

func (TimeTrigger) GetType() TaskTriggerType

type Trigger

type Trigger interface {
	GetEnabled() bool
	GetEndBoundary() time.Time
	GetExecutionTimeLimit() period.Period
	GetID() string
	GetRepetitionDuration() period.Period
	GetRepetitionInterval() period.Period
	GetStartBoundary() time.Time
	GetStopAtDurationEnd() bool
	GetType() TaskTriggerType
}

type Week

type Week uint8

Week specifies what week of the month a task will run on.

const (
	First Week = 1 << iota
	Second
	Third
	Fourth
	LastWeek
	AllWeeks Week = (1 << 5) - 1
)

func (Week) String

func (w Week) String() string

type WeekInterval

type WeekInterval uint8

WeekInterval specifies if a task runs every week or every other week.

const (
	EveryWeek      WeekInterval = 1
	EveryOtherWeek WeekInterval = 2
)

func (WeekInterval) String

func (w WeekInterval) String() string

type WeeklyTrigger

type WeeklyTrigger struct {
	TaskTrigger
	DaysOfWeek   DayOfWeek     // the days of the week in which the task runs
	RandomDelay  period.Period // a delay time that is randomly added to the start time of the trigger
	WeekInterval WeekInterval  // the interval between the weeks in the schedule
}

WeeklyTrigger triggers the task on a weekly schedule. The time of day that the task is started is set by StartBoundary, which must be set. https://docs.microsoft.com/en-us/windows/desktop/api/taskschd/nn-taskschd-iweeklytrigger

func (WeeklyTrigger) GetType

func (WeeklyTrigger) GetType() TaskTriggerType

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL