Automatically delete scheduled task using Python and Task Scheduler

101 Views Asked by At

I am working on a Python script to create tasks in the Windows Task Scheduler using the win32com.client module. I want to include functionality to automatically delete these tasks after a certain period. Task scheduling function works fine.

I've tried to set the task to delete after a specified time using set_delete_expired_task_after, but it doesn't seem to work as expected.

How can I properly set up automatic deletion of scheduled tasks in Python?

import datetime
import win32com.client


def create_task(
    name: str,
    description: str,
    date: str,
    hour: str,
    frequency: str,
    path_to_executable: str,
    path_to_execution_folder: str,
):
    """Function responsible for create a task on the task scheduler

    Args:
        name (str): Name of the task
        description (str): Task description
        date (str): Date that the task should be executed, must follow the pattern "YYYY-mm-dd"
        hour (str): Hour that the automation shoud be executed, must follow the pattern "HH:mm:ss"
        frequency (str): Frequency that the task will run, could be ["Unique", "Daily", "Weekly", "Monthly"]
        path_to_executable (str): Path to the automation exe file.
        path_to_execution_folder (str): Path to where the task scheduler should start from
    """
    scheduler = win32com.client.Dispatch("Schedule.Service")
    scheduler.Connect()

    rootFolder = scheduler.GetFolder(f"\\RPA\\{frequency}")

    taskDef = scheduler.NewTask(0)
    taskDef.RegistrationInfo.Description = description

    # Task properties configurations

    # Task config
    execAction = taskDef.Actions.Create(0)  # 0 means executable action
    execAction.Path = rf"{path_to_executable}"
    execAction.WorkingDirectory = rf"{path_to_execution_folder}"

    # Define the trigger
    trigger = taskDef.Triggers.Create(1)  # 1 means Initialization trigger
    trigger.StartBoundary = f"{date}T{hour}"

    date_to_expire = datetime.datetime.fromisoformat(
        f"{date}T{hour}"
    ) + datetime.timedelta(minutes=2)
    trigger.EndBoundary = date_to_expire.isoformat()

    rootFolder.RegisterTaskDefinition(
        name,  # Task name
        taskDef,
        6,  # Updates the task if already exists
        None,  # User Name (None for the actual user)
        None,  # Password (None for the actual password)
        3,  # Interactive Logon
    )


def set_delete_expired_task_after(
    task_name: str, task_folder: str, expiration_delay: str
):
    """Function responsible for deletion of expired tasks on task scheduler

    Args:
        task_name (str): Name of the task
        task_folder (str): Folder where the task is set on the task scheduler
        expiration_delay (str): Expiration timeout, must follow the pattern "PnM".
    """
    scheduler = win32com.client.Dispatch("Schedule.Service")
    scheduler.Connect()

    rootFolder = scheduler.GetFolder(f"\\RPA\\{task_folder}")
    task = rootFolder.GetTask(task_name)

    settings = task.Settings

    settingsXml = settings.Xml
    settingsXml = settingsXml.replace(
        "</Settings>",
        f"<DeleteExpiredTaskAfter>{expiration_delay}</DeleteExpiredTaskAfter></Settings>",
    )
    settings.Xml = settingsXml

    task.Settings = settings
    task.RegisterChanges()


# Create the task
path_executable = r"C:\Users\davi_vieira\OneDrive\Documents\Executaveis_automacoes\dist\importacoes_credito\importacoes_credito.exe"
path_folder = r"C:\Users\davi_vieira\OneDrive\Documents\Executaveis_automacoes\dist\importacoes_credito"

create_task(
    "Foo",
    "testable execution",
    "2023-12-08",
    "12:05:00",
    "Daily",
    path_executable,
    path_folder,
)

set_delete_expired_task_after("Foo", "Daily", "P7D")

Error messages:

Traceback (most recent call last):
File "c:\Users\davi_vieira\OneDrive\Documents\XXX_XXX_automation\src\helpers\task_scheduler.py", line 94, in <module>
set_delete_expired_task_after("Teste", "Diario", "P7D")
File "c:\Users\davi_vieira\OneDrive\Documents\XXXX_XXXX_automation\src\helpers\task_scheduler.py", line 68, in set_delete_expired_task_after
settings = task.Settings
>                ^^^^^^^^^^^^^
File "C:\Users\davi_vieira\OneDrive\Documents\XXXX_XXXX_automation\.venv\Lib\site-packages\win32com\client\dynamic.py", line 638, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: GetTask.Settings
0

There are 0 best solutions below