├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples └── open_notepad.rs └── src ├── lib.rs ├── registered_task.rs └── task ├── mod.rs ├── task_action.rs ├── task_settings.rs ├── task_trigger.rs └── trigger.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "windows-taskscheduler" 3 | version = "0.2.0" 4 | edition = "2021" 5 | 6 | [dependencies.windows] 7 | version = "0.37" 8 | features = [ 9 | "Win32_System_Com", 10 | "Win32_System_TaskScheduler", 11 | "Win32_System_Ole", 12 | "Win32_Foundation", 13 | ] 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # windows task scheduler api for rust 2 | 3 | This was made for personal use so know that it's very limited 4 | 5 | ## Usage 6 | In your Cargo.toml 7 | ```rust 8 | windows-taskscheduler = { git = "https://github.com/j-hc/windows-taskscheduler-api-rust.git" } 9 | ``` 10 | 11 | Also have a look at the [example here](/examples/open_notepad.rs) 12 | # 13 | ```rust 14 | use std::time::Duration; 15 | use windows_taskscheduler::{TaskAction, RunLevel, Task, TaskIdleTrigger}; 16 | 17 | 18 | let trigger = TaskIdleTrigger::new( 19 | "idletrigger", 20 | Duration::from_secs(3 * 60), 21 | true, 22 | Duration::from_secs(10 * 60), 23 | ); 24 | let action = TaskAction::new("action", "notepad.exe", "", ""); 25 | Task::new(r"\")? 26 | .idle_trigger(trigger)? 27 | .exec_action(action)? 28 | .principal(RunLevel::LUA, "", "")? 29 | .set_hidden(false)? 30 | .register("open notepad when idle")?; 31 | 32 | ``` 33 | -------------------------------------------------------------------------------- /examples/open_notepad.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | use windows_taskscheduler::RegisteredTask; 3 | use windows_taskscheduler::TaskAction; 4 | use windows_taskscheduler::TaskLogonTrigger; 5 | use windows_taskscheduler::{RunLevel, Task, TaskIdleTrigger}; 6 | 7 | fn main() -> windows_taskscheduler::Result<()> { 8 | const TASK_NAME: &str = "open_notepad_when_idle"; 9 | 10 | let _registered_task = create_task(TASK_NAME)?; 11 | let registered_task = Task::get_task(r"\", TASK_NAME)?; 12 | 13 | assert_eq!(registered_task.name()?, registered_task.name()?); 14 | 15 | registered_task.run_raw()?; 16 | 17 | println!("{:?}", registered_task.last_run_time()?); 18 | println!("{:?}", registered_task.next_run_time()?); 19 | 20 | Task::delete_task(r"\", TASK_NAME)?; 21 | 22 | Ok(()) 23 | } 24 | 25 | fn create_task(name: &str) -> windows_taskscheduler::Result { 26 | let idle_trigger = TaskIdleTrigger::new( 27 | "idletrigger", 28 | Duration::from_secs(3 * 60), 29 | true, 30 | Duration::from_secs(10 * 60), 31 | ); 32 | 33 | // requires admin rights 34 | let _logon_trigger = TaskLogonTrigger::new( 35 | "logontrigger", 36 | Duration::from_secs(3 * 60), 37 | true, 38 | Duration::from_secs(10), 39 | Duration::from_secs(1), 40 | ); 41 | 42 | let action = TaskAction::new("action", "notepad.exe", "", ""); 43 | Task::new(r"\")? 44 | .idle_trigger(idle_trigger)? 45 | // .logon_trigger(logon_trigger)? 46 | .exec_action(action)? 47 | .principal(RunLevel::LUA, "", "")? 48 | .set_hidden(false)? 49 | .register(name) 50 | } 51 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | mod task; 2 | pub use task::{ 3 | task_action::TaskAction, 4 | task_settings::TaskSettings, 5 | task_trigger::{TaskIdleTrigger, TaskLogonTrigger}, 6 | RunLevel, Task, 7 | }; 8 | 9 | mod registered_task; 10 | pub use registered_task::{RegisteredTask, TaskState}; 11 | 12 | pub use windows::core::{Error, Result}; 13 | pub use windows::Win32::Foundation::SYSTEMTIME; 14 | -------------------------------------------------------------------------------- /src/registered_task.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | use windows::core::Result; 3 | use windows::Win32::Foundation::{BSTR, SYSTEMTIME}; 4 | use windows::Win32::System::TaskScheduler::{ 5 | IRegisteredTask, IRunningTask, TASK_STATE_DISABLED, TASK_STATE_QUEUED, TASK_STATE_READY, 6 | TASK_STATE_RUNNING, TASK_STATE_UNKNOWN, 7 | }; 8 | 9 | pub enum TaskState { 10 | TaskStateUnknown, 11 | TaskStateDisabled, 12 | TaskStateQueued, 13 | TaskStateReady, 14 | TaskStateRunning, 15 | } 16 | 17 | fn date_to_dur(oledate: f64) -> Duration { 18 | let mut num: i64 = ((oledate * 86400000.0) + (if oledate >= 0.0 { 0.5 } else { -0.5 })) as i64; 19 | if num < 0 { 20 | num -= (num % 0x5265c00) * 2; 21 | } 22 | num += 0x3680b5e1fc00 - 0x3883122cd800; 23 | Duration::from_secs(num as u64) 24 | } 25 | 26 | pub struct RegisteredTask { 27 | pub(crate) registered_task: IRegisteredTask, 28 | } 29 | impl RegisteredTask { 30 | pub fn name(&self) -> Result { 31 | unsafe { self.registered_task.Name().map(|s| s.to_string()) } 32 | } 33 | 34 | pub fn path(&self) -> Result { 35 | unsafe { self.registered_task.Path().map(|s| s.to_string()) } 36 | } 37 | 38 | pub fn state(&self) -> Result { 39 | unsafe { 40 | use TaskState::*; 41 | self.registered_task.State().map(|s| match s { 42 | TASK_STATE_UNKNOWN => TaskStateUnknown, 43 | TASK_STATE_DISABLED => TaskStateDisabled, 44 | TASK_STATE_QUEUED => TaskStateQueued, 45 | TASK_STATE_READY => TaskStateReady, 46 | TASK_STATE_RUNNING => TaskStateRunning, 47 | _ => unreachable!(), 48 | }) 49 | } 50 | } 51 | 52 | pub fn enabled(&self) -> Result { 53 | unsafe { self.registered_task.Enabled().map(|s| s != 0) } 54 | } 55 | 56 | pub fn set_enabled(&self, enabled: bool) -> Result<()> { 57 | unsafe { self.registered_task.SetEnabled(enabled as i16) } 58 | } 59 | 60 | pub fn run_raw(&self) -> Result { 61 | // TODO: support variants 62 | unsafe { self.registered_task.Run(None) } 63 | } 64 | 65 | pub fn runex_raw(&self, flags: i32, sessionid: i32, user: &str) -> Result { 66 | // TODO: support variants 67 | unsafe { 68 | let user = BSTR::from(user); 69 | self.registered_task.RunEx(None, flags, sessionid, user) 70 | } 71 | } 72 | 73 | pub fn last_run_time(&self) -> Result { 74 | let date = unsafe { self.registered_task.LastRunTime()? }; 75 | Ok(date_to_dur(date)) 76 | } 77 | 78 | pub fn last_task_result_raw(&self) -> Result { 79 | unsafe { self.registered_task.LastTaskResult() } 80 | } 81 | pub fn number_of_missed_runs(&self) -> Result { 82 | unsafe { self.registered_task.NumberOfMissedRuns() } 83 | } 84 | 85 | pub fn next_run_time(&self) -> Result { 86 | let date = unsafe { self.registered_task.NextRunTime()? }; 87 | Ok(date_to_dur(date)) 88 | } 89 | 90 | pub fn xml(&self) -> Result { 91 | unsafe { self.registered_task.Xml().map(|s| s.to_string()) } 92 | } 93 | 94 | pub fn stop(&self) -> Result<()> { 95 | unsafe { self.registered_task.Stop(0)? }; 96 | Ok(()) 97 | } 98 | 99 | pub fn get_run_times( 100 | &self, 101 | pst_start: &SYSTEMTIME, 102 | pst_end: &SYSTEMTIME, 103 | ) -> Result<(u32, SYSTEMTIME)> { 104 | unsafe { 105 | let mut pcount = 0; 106 | let mut pruntimes = SYSTEMTIME::default(); 107 | 108 | // let systime_def = SYSTEMTIME { 109 | // wYear: 1601, 110 | // wDay: 1, 111 | // wMonth: 1, 112 | // ..Default::default() 113 | // }; 114 | // let systime_infinite = SYSTEMTIME { 115 | // wYear: 30827, 116 | // wDay: 1, 117 | // wMonth: 1, 118 | // ..Default::default() 119 | // }; 120 | // let pst_start = pst_start.unwrap_or(&systime_def); 121 | // let pst_end = pst_end.unwrap_or(&systime_infinite); 122 | 123 | self.registered_task.GetRunTimes( 124 | pst_start as *const SYSTEMTIME, 125 | pst_end as *const SYSTEMTIME, 126 | &mut pcount as *mut u32, 127 | &mut pruntimes as *mut _ as *mut _, 128 | )?; 129 | Ok((pcount, pruntimes)) 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/task/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod task_action; 2 | pub mod task_settings; 3 | pub mod task_trigger; 4 | 5 | use crate::task::task_action::TaskAction; 6 | use crate::task::task_settings::TaskSettings; 7 | use crate::RegisteredTask; 8 | use task_trigger::{TaskIdleTrigger, TaskLogonTrigger}; 9 | 10 | use windows::core::{Interface, Result}; 11 | use windows::Win32::Foundation::BSTR; 12 | use windows::Win32::System::Com::{ 13 | CoCreateInstance, CoInitializeEx, CLSCTX_ALL, COINIT_MULTITHREADED, VARIANT, 14 | }; 15 | use windows::Win32::System::TaskScheduler::{ 16 | IAction, IActionCollection, IExecAction, IIdleSettings, IIdleTrigger, ILogonTrigger, 17 | IPrincipal, IRegistrationInfo, IRepetitionPattern, ITaskDefinition, ITaskFolder, ITaskService, 18 | ITaskSettings, ITriggerCollection, TaskScheduler, TASK_ACTION_EXEC, TASK_CREATE_OR_UPDATE, 19 | TASK_LOGON_INTERACTIVE_TOKEN, TASK_RUNLEVEL_HIGHEST, TASK_RUNLEVEL_LUA, TASK_TRIGGER_IDLE, 20 | TASK_TRIGGER_LOGON, 21 | }; 22 | 23 | pub enum RunLevel { 24 | HIGHEST, 25 | LUA, 26 | } 27 | 28 | pub struct Task { 29 | task_definition: ITaskDefinition, 30 | reg_info: IRegistrationInfo, 31 | triggers: ITriggerCollection, 32 | actions: IActionCollection, 33 | settings: ITaskSettings, 34 | folder: ITaskFolder, 35 | } 36 | impl Task { 37 | fn get_task_service() -> Result { 38 | // im probably leaking com objects memory by not releasing them but meh 39 | unsafe { 40 | CoInitializeEx(std::ptr::null_mut(), COINIT_MULTITHREADED)?; 41 | 42 | let task_service: ITaskService = CoCreateInstance(&TaskScheduler, None, CLSCTX_ALL)?; 43 | task_service.Connect( 44 | VARIANT::default(), 45 | VARIANT::default(), 46 | VARIANT::default(), 47 | VARIANT::default(), 48 | )?; 49 | Ok(task_service) 50 | } 51 | } 52 | 53 | pub fn new(path: &str) -> Result { 54 | unsafe { 55 | let task_service = Self::get_task_service()?; 56 | 57 | let task_definition: ITaskDefinition = task_service.NewTask(0)?; 58 | let triggers: ITriggerCollection = task_definition.Triggers()?; 59 | let reg_info: IRegistrationInfo = task_definition.RegistrationInfo()?; 60 | let actions: IActionCollection = task_definition.Actions()?; 61 | let settings: ITaskSettings = task_definition.Settings()?; 62 | let folder: ITaskFolder = task_service.GetFolder(BSTR::from(path))?; 63 | 64 | Ok(Self { 65 | task_definition, 66 | reg_info, 67 | triggers, 68 | actions, 69 | settings, 70 | folder, 71 | }) 72 | } 73 | } 74 | 75 | pub fn from_xml(self, xml: String) -> Result { 76 | unsafe { 77 | let task_service = Self::get_task_service()?; 78 | let task_definition: ITaskDefinition = task_service.NewTask(0)?; 79 | task_definition.SetXmlText(BSTR::from(xml))?; 80 | } 81 | Ok(self) 82 | } 83 | 84 | pub fn register(self, name: &str) -> Result { 85 | unsafe { 86 | let registered_task = self.folder.RegisterTaskDefinition( 87 | BSTR::from(name), 88 | &self.task_definition, 89 | TASK_CREATE_OR_UPDATE.0, 90 | None, 91 | None, 92 | TASK_LOGON_INTERACTIVE_TOKEN, 93 | None, 94 | )?; 95 | self.settings.SetEnabled(1)?; 96 | Ok(RegisteredTask { registered_task }) 97 | } 98 | } 99 | 100 | pub fn set_hidden(self, is_hidden: bool) -> Result { 101 | unsafe { self.settings.SetHidden(is_hidden as i16)? } 102 | Ok(self) 103 | } 104 | 105 | pub fn author(self, author: &str) -> Result { 106 | unsafe { self.reg_info.SetAuthor(BSTR::from(author))? } 107 | Ok(self) 108 | } 109 | 110 | pub fn description(self, description: &str) -> Result { 111 | unsafe { self.reg_info.SetDescription(BSTR::from(description))? } 112 | Ok(self) 113 | } 114 | 115 | pub fn idle_trigger(self, idle_trigger: TaskIdleTrigger) -> Result { 116 | unsafe { 117 | let trigger = self.triggers.Create(TASK_TRIGGER_IDLE)?; 118 | 119 | let i_idle_trigger: IIdleTrigger = trigger.cast::()?; 120 | i_idle_trigger.SetId(idle_trigger.id)?; 121 | i_idle_trigger.SetEnabled(1)?; 122 | i_idle_trigger.SetExecutionTimeLimit(idle_trigger.execution_time_limit)?; 123 | 124 | let repetition: IRepetitionPattern = i_idle_trigger.Repetition()?; 125 | repetition.SetInterval(idle_trigger.repetition_interval)?; 126 | repetition.SetStopAtDurationEnd(idle_trigger.repetition_stop_at_duration_end)?; 127 | } 128 | Ok(self) 129 | } 130 | 131 | pub fn logon_trigger(self, logon_trigger: TaskLogonTrigger) -> Result { 132 | unsafe { 133 | let trigger = self.triggers.Create(TASK_TRIGGER_LOGON)?; 134 | let i_logon_trigger = trigger.cast::()?; 135 | i_logon_trigger.SetId(logon_trigger.id)?; 136 | i_logon_trigger.SetEnabled(1)?; 137 | i_logon_trigger.SetExecutionTimeLimit(logon_trigger.execution_time_limit)?; 138 | 139 | let repetition = i_logon_trigger.Repetition()?; 140 | repetition.SetInterval(logon_trigger.repetition_interval)?; 141 | repetition.SetStopAtDurationEnd(logon_trigger.repetition_stop_at_duration_end)?; 142 | 143 | i_logon_trigger.SetDelay(logon_trigger.delay)?; 144 | } 145 | Ok(self) 146 | } 147 | 148 | pub fn principal(self, run_level: RunLevel, id: &str, user_id: &str) -> Result { 149 | unsafe { 150 | let principal: IPrincipal = self.task_definition.Principal()?; 151 | match run_level { 152 | RunLevel::HIGHEST => principal.SetRunLevel(TASK_RUNLEVEL_HIGHEST)?, 153 | RunLevel::LUA => principal.SetRunLevel(TASK_RUNLEVEL_LUA)?, 154 | } 155 | principal.SetId(BSTR::from(id))?; 156 | principal.SetUserId(BSTR::from(user_id))?; 157 | } 158 | Ok(self) 159 | } 160 | 161 | pub fn settings(self, task_settings: TaskSettings) -> Result { 162 | unsafe { 163 | self.settings 164 | .SetRunOnlyIfIdle(task_settings.run_only_if_idle)?; 165 | self.settings.SetWakeToRun(task_settings.wake_to_run)?; 166 | self.settings 167 | .SetExecutionTimeLimit(task_settings.execution_time_limit)?; 168 | self.settings 169 | .SetDisallowStartIfOnBatteries(task_settings.disallow_start_if_on_batteries)?; 170 | self.settings 171 | .SetAllowHardTerminate(task_settings.allow_hard_terminate)?; 172 | 173 | if let Some(idle_settings) = task_settings.idle_settings { 174 | let idle_s: IIdleSettings = self.settings.IdleSettings()?; 175 | idle_s.SetStopOnIdleEnd(idle_settings.stop_on_idle_end)?; 176 | idle_s.SetRestartOnIdle(idle_settings.restart_on_idle)?; 177 | idle_s.SetIdleDuration(idle_settings.idle_duration)?; 178 | idle_s.SetWaitTimeout(idle_settings.wait_timeout)?; 179 | } 180 | } 181 | Ok(self) 182 | } 183 | 184 | pub fn exec_action(self, task_action: TaskAction) -> Result { 185 | unsafe { 186 | let action: IAction = self.actions.Create(TASK_ACTION_EXEC)?; 187 | let exec_action: IExecAction = action.cast()?; 188 | 189 | exec_action.SetPath(task_action.path)?; 190 | exec_action.SetId(task_action.id)?; 191 | exec_action.SetWorkingDirectory(task_action.working_dir)?; 192 | exec_action.SetArguments(task_action.args)?; 193 | } 194 | Ok(self) 195 | } 196 | 197 | pub fn get_task(path: &str, name: &str) -> Result { 198 | unsafe { 199 | let task_service = Self::get_task_service()?; 200 | let folder = task_service.GetFolder(BSTR::from(path))?; 201 | let registered_task = folder.GetTask(BSTR::from(name))?; 202 | Ok(RegisteredTask { registered_task }) 203 | } 204 | } 205 | 206 | pub fn delete_task(path: &str, name: &str) -> Result<()> { 207 | unsafe { 208 | let task_service = Self::get_task_service()?; 209 | let folder = task_service.GetFolder(BSTR::from(path))?; 210 | folder.DeleteTask(BSTR::from(name), 0)?; 211 | } 212 | Ok(()) 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /src/task/task_action.rs: -------------------------------------------------------------------------------- 1 | use windows::Win32::Foundation::BSTR; 2 | 3 | pub struct TaskAction { 4 | pub(crate) id: BSTR, 5 | pub(crate) path: BSTR, 6 | pub(crate) working_dir: BSTR, 7 | pub(crate) args: BSTR, 8 | } 9 | impl TaskAction { 10 | pub fn new(id: &str, path: &str, working_dir: &str, args: &str) -> Self { 11 | Self { 12 | id: id.into(), 13 | path: path.into(), 14 | working_dir: working_dir.into(), 15 | args: args.into(), 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/task/task_settings.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | use windows::Win32::Foundation::BSTR; 3 | 4 | pub struct IdleSettings { 5 | pub(crate) stop_on_idle_end: i16, 6 | pub(crate) restart_on_idle: i16, 7 | pub(crate) idle_duration: BSTR, 8 | pub(crate) wait_timeout: BSTR, 9 | } 10 | impl IdleSettings { 11 | pub fn new( 12 | stop_on_idle_end: bool, 13 | restart_on_idle: bool, 14 | idle_duration: Duration, 15 | wait_timeout: Duration, 16 | ) -> Self { 17 | Self { 18 | stop_on_idle_end: stop_on_idle_end as i16, 19 | restart_on_idle: restart_on_idle as i16, 20 | idle_duration: format!("PT{}S", idle_duration.as_secs()).into(), 21 | wait_timeout: format!("PT{}S", wait_timeout.as_secs()).into(), 22 | } 23 | } 24 | } 25 | 26 | pub struct TaskSettings { 27 | pub(crate) idle_settings: Option, 28 | pub(crate) run_only_if_idle: i16, 29 | pub(crate) wake_to_run: i16, 30 | pub(crate) execution_time_limit: BSTR, 31 | pub(crate) disallow_start_if_on_batteries: i16, 32 | pub(crate) allow_hard_terminate: i16, 33 | } 34 | impl TaskSettings { 35 | pub fn new( 36 | idle_settings: Option, 37 | run_only_if_idle: bool, 38 | wake_to_run: bool, 39 | execution_time_limit: Duration, 40 | disallow_start_if_on_batteries: bool, 41 | allow_hard_terminate: bool, 42 | ) -> Self { 43 | Self { 44 | idle_settings, 45 | run_only_if_idle: run_only_if_idle as i16, 46 | wake_to_run: wake_to_run as i16, 47 | execution_time_limit: format!("PT{}S", execution_time_limit.as_secs()).into(), 48 | disallow_start_if_on_batteries: disallow_start_if_on_batteries as i16, 49 | allow_hard_terminate: allow_hard_terminate as i16, 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/task/task_trigger.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | use windows::Win32::Foundation::BSTR; 3 | 4 | pub struct TaskIdleTrigger { 5 | pub(crate) id: BSTR, 6 | pub(crate) repetition_interval: BSTR, 7 | pub(crate) repetition_stop_at_duration_end: i16, 8 | pub(crate) execution_time_limit: BSTR, 9 | } 10 | impl TaskIdleTrigger { 11 | pub fn new( 12 | id: &str, 13 | repetition_interval: Duration, 14 | repetition_stop_at_duration_end: bool, 15 | execution_time_limit: Duration, 16 | ) -> Self { 17 | Self { 18 | id: id.into(), 19 | repetition_interval: format!("PT{}S", repetition_interval.as_secs()).into(), 20 | repetition_stop_at_duration_end: repetition_stop_at_duration_end as i16, 21 | execution_time_limit: format!("PT{}S", execution_time_limit.as_secs()).into(), 22 | } 23 | } 24 | } 25 | 26 | pub struct TaskLogonTrigger { 27 | pub(crate) id: BSTR, 28 | pub(crate) repetition_interval: BSTR, 29 | pub(crate) repetition_stop_at_duration_end: i16, 30 | pub(crate) execution_time_limit: BSTR, 31 | pub(crate) delay: BSTR, 32 | } 33 | impl TaskLogonTrigger { 34 | pub fn new( 35 | id: &str, 36 | repetition_interval: Duration, 37 | repetition_stop_at_duration_end: bool, 38 | execution_time_limit: Duration, 39 | delay: Duration, 40 | ) -> Self { 41 | Self { 42 | id: id.into(), 43 | repetition_interval: format!("PT{}S", repetition_interval.as_secs()).into(), 44 | repetition_stop_at_duration_end: repetition_stop_at_duration_end as i16, 45 | execution_time_limit: format!("PT{}S", execution_time_limit.as_secs()).into(), 46 | delay: format!("PT{}S", delay.as_secs()).into(), 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/task/trigger.rs: -------------------------------------------------------------------------------- 1 | macro_rules! generate_triggers { 2 | ($t:ty, $name:ident, $tc:ident) => { 3 | struct $name { 4 | inner: $t, 5 | } 6 | impl $name { 7 | fn new(triggers: ::windows::Win32::System::TaskScheduler::ITriggerCollection) -> Self { 8 | let inner = unsafe { 9 | let trigger = triggers 10 | .Create(::windows::Win32::System::TaskScheduler::$tc) 11 | .unwrap(); 12 | trigger.cast::<$t>().unwrap() 13 | }; 14 | Self { inner } 15 | } 16 | 17 | pub fn r#type(&self) -> ::windows::Win32::System::TaskScheduler::TASK_TRIGGER_TYPE2 { 18 | let mut ttt = 19 | ::windows::Win32::System::TaskScheduler::TASK_TRIGGER_TYPE2::default(); 20 | unsafe { 21 | self.inner 22 | .Type( 23 | &mut ttt 24 | as *mut ::windows::Win32::System::TaskScheduler::TASK_TRIGGER_TYPE2, 25 | ) 26 | .unwrap() 27 | }; 28 | ttt 29 | } 30 | } 31 | }; 32 | } 33 | generate_triggers!( 34 | windows::Win32::System::TaskScheduler::IIdleTrigger, 35 | IdleTrigger, 36 | TASK_TRIGGER_IDLE 37 | ); 38 | 39 | generate_triggers!( 40 | windows::Win32::System::TaskScheduler::ILogonTrigger, 41 | LogonTrigger, 42 | TASK_TRIGGER_LOGON 43 | ); 44 | generate_triggers!( 45 | windows::Win32::System::TaskScheduler::ITimeTrigger, 46 | TimeTrigger, 47 | TASK_TRIGGER_TIME 48 | ); 49 | --------------------------------------------------------------------------------