Solved

Delete a scheduled task with vb.net

Posted on 2008-10-14
19
2,144 Views
Last Modified: 2013-11-26
I have developed a small app. in Visual Studio 2008 and vb.net,  where users can create scheduled tasks to run reports at selected times from another application. I have used TaskScheduler 1.0 and The Code Project's Task Scheduler Class Library for .NET for both Vista and XP installations. This all works fine and the scheduled tasks run with no problems. My problem is the code that deletes a scheduled task on request but which does not delete the task. Any ideas please? (code attached). I don't get any errors when the sub runs and I can see the the Task names in the Windows\Tasks folder.
Sub DeleteTasks()
        Dim st As ScheduledTasks = New ScheduledTasks
        Dim taskNames = st.GetTaskNames
        Dim name As String
        For Each name In taskNames
            If name = "MyFirst.job" Or name = "MySecond.job" Then
                Dim t As Task = st.OpenTask(name)
                st.DeleteTask(name)
            End If
        Next
        st.Dispose()
    End Sub

Open in new window

0
Comment
Question by:Al230762
  • 10
  • 9
19 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22710482
0
 

Author Comment

by:Al230762
ID: 22710644
Thanks emoreau. I 'm sorry but I don't see how that answers my question. Could you explain further please?
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22710677
In the demo I have, I have a delete button that deletes the selected task.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:Al230762
ID: 22711113
Yes, i can see that Delete button in the demo but unfortunately I'm not using the Edanmo.Taskscheduler. I really need to know what's wrong with the code I'm actiually using. Thanks anyway.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22711362
I just downloaded "A New Task Scheduler Class Library for .NET" (http://www.codeproject.com/KB/cs/tsnewlib.aspx) which is a revamp version of the article you refered and it is working great for me:

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim st As ScheduledTasks = New ScheduledTasks
        For Each name As String In st.GetTaskNames
            If name = "Test.job" Then
                If st.DeleteTask(name) Then
                    MessageBox.Show("deleted")
                Else
                    MessageBox.Show("NOT deleted")
                End If
            End If
        Next
        st.Dispose()
    End Sub
0
 

Author Comment

by:Al230762
ID: 22711681
Thanks for that. I have replaced my code with exactly the code you posted. The filename exists as i step through the code and matches exactly the file name quoted in the "If name =..." line. The debugger moves on to the the "If st.DeleteTask..." line then jumps straight to  "MessageBox.Show("NOT deleted")". There are no problems with Accounts or permissions and the user has no problem creating the tasks initially.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22711719
probably the task is still allocated. try to stop your application and restart it.
0
 

Author Comment

by:Al230762
ID: 22711933
What does "allocated" mean in this context? Is there a way of un-allocating before deleting? The user of my app. can create a scheduled task but may decide immediately to delete that task and create a new one so they shouldn't need to close and re-open the app. to do that.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22711998
be sure that you dispose all objects that have this method and that you set all your objects to nothing

to be sure that the problem is related to allocated (in-memory, referenced, ...) object, have you tried to close the application, restart it and try to delete your task?
0
 

Author Comment

by:Al230762
ID: 22712247
Yes - have restarted and ensured that this is the first function to be called after opening that involves the TaskScheduler. Still refuses to delete.
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22712308
Then I don't know.

Can you paste the code you use to create your task?
Have you tried the library from "A New Task Scheduler Class Library for .NET" (http://www.codeproject.com/KB/cs/tsnewlib.aspx) ?
Are you able to delete this task from the Windows dialog?
0
 

Author Comment

by:Al230762
ID: 22713817
Some further info. I believe this is a Vista and TaskScheduler 2.0 -related problem. The tasks were running fine. I could also see the tasks in the Vista Task Scheduler (although not sure how I achieved that). I deleted the tasks from the Windows\Tasks folder and recreated the tasks from my app. with the code (attached).

Now I can see the re-created tasks in the Windows\Tasks folder but CANNOT see them in the Vista Task Scheduler 2.0 and the tasks also now do NOT run at all.. However, the DeleteTask function DOES now work. So it appears that having the Vista Task Scheduler 2.0 somehow recognise the Task Scheduler 1 tasks allows the tasks to be run correctly but does not allow them to be deleted with the st.DeleteTask(name)  code. Hope that makes sense.
Sub CreateScheduledTasks()
        'uses Taskscheduler 1.0
        Dim appfilepath As String = Application.StartupPath & "\PMWdataUpload.exe"
        Dim st As ScheduledTasks = New ScheduledTasks
        Dim t As Task
        Try
            t = st.CreateTask("PMWstudentDataUpload")
        Catch ex As Exception
      
          If ex.Message.StartsWith("The task") AndAlso ex.Message.EndsWith("already exists.") Then
                st.DeleteTask("PMWstudentDataUpload.job")
            End If
        End Try
        'Fill in the program info
        t.ApplicationName = appfilepath
        t.Parameters = "student"
        t.Comment = "Run report from SIMS and upload to Provision Map Writer"
        t.MaxRunTime = New TimeSpan(0, 30, 0)
       
        If gpPupils.Value > 0 Then
            Select Case Me.gpPupils.Value
                'Allow the task to run for no more than 30 minutes.
                Case 1
                    t.Triggers.Add(New DailyTrigger(9, 7))
                Case 2
                    t.Triggers.Add(New WeeklyTrigger(10, 30, DaysOfTheWeek.Monday))
                Case 3             
                    t.Triggers.Add(New MonthlyDOWTrigger(10, 30, DaysOfTheWeek.Monday, WhichWeek.FirstWeek))
            End Select
        End If
 
        t.Flags = TaskFlags.RunIfConnectedToInternet
 
        ' Save the changes that have been made.
        t.Save()
        ' Close the task to release its COM resources.
        t.Close()
        ' Dispose the ScheduledTasks to release its COM resources.
        st.Dispose()
 
        Dim appfilepath2 As String = Application.StartupPath & "\PMWdataUpload.exe"
        Dim st2 As ScheduledTasks = New ScheduledTasks
        Dim t2 As Task
        Try
            t2 = st2.CreateTask("PMWstaffDataUpload")
 
       If ex.Message.StartsWith("The task") AndAlso ex.Message.EndsWith("already exists.") Then
                st.DeleteTask("PMWstudentDataUpload.job")
            End If
 
        'Fill in the program info
 
        t2.ApplicationName = appfilepath2
        t2.Parameters = "staff"
 
 
        t2.Comment = "Run report from SIMS and upload to Provision Map Writer"
 
        t2.MaxRunTime = New TimeSpan(0, 30, 0)
 
 
        If gpStaff.Value > 0 Then
            Select Case Me.gpStaff.Value
                'Allow the task to run for no more than 30 minutes.
                Case 1, 4
                    t2.Triggers.Add(New DailyTrigger(9, 10))
                Case 2, 5
                    t2.Triggers.Add(New WeeklyTrigger(10, 30, DaysOfTheWeek.Monday))
                Case 3, 6
                    t2.Triggers.Add(New MonthlyDOWTrigger(10, 30, DaysOfTheWeek.Monday, WhichWeek.FirstWeek))
            End Select
        End If
 
 
        t2.Flags = TaskFlags.RunIfConnectedToInternet
 
        ' Save the changes that have been made.
        t2.Save()
        ' Close the task to release its COM resources.
        t2.Close()
        ' Dispose the ScheduledTasks to release its COM resources.
        st2.Dispose()
    End Sub

Open in new window

0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22714004
your code has errors! You have a Try on line 44 with no Catch and End Try
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22714021
it seems that starting at line 41, it is a duplicate! What is the real code to create a task?
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 22714045
this code is working for me on XP:

Option Strict On

Imports TaskScheduler

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim st As ScheduledTasks = New ScheduledTasks
        Dim taskNames As String() = st.GetTaskNames
        'Dim name As String
        ListBox1.Items.Clear()
        For Each name As String In taskNames
            ListBox1.Items.Add(name)
            'If name = "MyFirst.job" Or name = "MySecond.job" Then
            '    Dim t As Task = st.OpenTask(name)
            '    st.DeleteTask(name)
            'End If
        Next
        st.Dispose()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim st As ScheduledTasks = New ScheduledTasks
        For Each name As String In st.GetTaskNames
            If name = "PMWstudentDataUpload.job" Then
                If st.DeleteTask(name) Then
                    MessageBox.Show("deleted")
                Else
                    MessageBox.Show("NOT deleted")
                End If
            End If
        Next
        st.Dispose()
        Button1.PerformClick()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        CreateScheduledTasks()
        Button1.PerformClick()
    End Sub

    Sub CreateScheduledTasks()
        'uses Taskscheduler 1.0
        Dim appfilepath As String = "Notepad.exe"  ' Application.StartupPath & "\PMWdataUpload.exe"
        Dim st As ScheduledTasks = New ScheduledTasks
        Dim t As Task = Nothing
        Try
            t = st.CreateTask("PMWstudentDataUpload")
        Catch ex As Exception

            If ex.Message.StartsWith("The task") AndAlso ex.Message.EndsWith("already exists.") Then
                st.DeleteTask("PMWstudentDataUpload.job")
            End If
        End Try
        'Fill in the program info
        t.ApplicationName = appfilepath
        t.Parameters = "student"
        t.Comment = "Run report from SIMS and upload to Provision Map Writer"
        t.MaxRunTime = New TimeSpan(0, 30, 0)

        'If gpPupils.Value > 0 Then
        '    Select Case Me.gpPupils.Value
        '        'Allow the task to run for no more than 30 minutes.
        '        Case 1
        '            t.Triggers.Add(New DailyTrigger(9, 7))
        '        Case 2
        '            t.Triggers.Add(New WeeklyTrigger(10, 30, DaysOfTheWeek.Monday))
        '        Case 3
        '            t.Triggers.Add(New MonthlyDOWTrigger(10, 30, DaysOfTheWeek.Monday, WhichWeek.FirstWeek))
        '    End Select
        'End If

        t.Flags = TaskFlags.RunIfConnectedToInternet

        ' Save the changes that have been made.
        t.Save()
        ' Close the task to release its COM resources.
        t.Close()
        ' Dispose the ScheduledTasks to release its COM resources.
        st.Dispose()
    End Sub

End Class
0
 

Author Comment

by:Al230762
ID: 22714643
Many thanks for your help with this so far. I apologise because a few lines of code were missing from my create schedulled task function - I have attached the FULL code and it does work fine for me too but only after adding user login details (see below).

I think, as I said before, the problem is with Vista and taskScheduler 2.0.

When these tasks are first created they do NOT appear in the Vista TaskScheduler 2.0 dialog and also they do not run at all. After I open them  with the  "t.DisplayForEdit()" command and add the current account login password, the tasks then appear in the Vista TaskScheduler 2.0 dialog and run perfectly but now they cannot be deleted with the "st.DeleteTask(name)" command. So there are 2 problems in Vista:
1) I need to find a way of adding the current account login password during the create task function and
2) i need to find a way of deleting those tasks using the CodeProject task Scheduler Class.
    Sub CreateScheduledTasks()
        'uses Taskscheduler 1.0
 
        Dim appfilepath As String = Application.StartupPath & "\PMWdataUpload.exe"
        Dim st As ScheduledTasks = New ScheduledTasks
 
        Dim t As Task
 
        Try
 
            t = st.CreateTask("PMWstudentDataUpload")
 
        Catch ex As Exception
            If ex.Message.StartsWith("The task") AndAlso ex.Message.EndsWith("already exists.") Then
                st.DeleteTask("PMWstudentDataUpload.job")
            End If
 
        End Try
 
        'Fill in the program info
 
        t.ApplicationName = appfilepath
        t.Parameters = "student"
        t.Comment = "Run report from SIMS and upload to Provision Map Writer"
        t.MaxRunTime = New TimeSpan(0, 30, 0)
       
        If gpPupils.Value > 0 Then
            Select Case Me.gpPupils.Value
                'Allow the task to run for no more than 30 minutes.
                Case 1
                    t.Triggers.Add(New DailyTrigger(18, 35))
                Case 2
                    t.Triggers.Add(New WeeklyTrigger(10, 30, DaysOfTheWeek.Monday))
                Case 3             
                    t.Triggers.Add(New MonthlyDOWTrigger(10, 30, DaysOfTheWeek.Monday, WhichWeek.FirstWeek))
            End Select
        End If
 
        t.Flags = TaskFlags.RunIfConnectedToInternet
 
        ' Save the changes that have been made.
        t.Save()
        ' Close the task to release its COM resources.
        t.Close()
        ' Dispose the ScheduledTasks to release its COM resources.
        st.Dispose()
 
 
        Dim appfilepath2 As String = Application.StartupPath & "\PMWdataUpload.exe"
        Dim st2 As ScheduledTasks = New ScheduledTasks
        Dim t2 As Task
        Try
 
            t2 = st2.CreateTask("PMWstaffDataUpload")
 
        Catch ex As Exception
    
           If ex.Message.StartsWith("The task") AndAlso ex.Message.EndsWith("already exists.") Then
                st.DeleteTask("PMWstaffDataUpload.job")
            End If
 
        End Try
 
        'Fill in the program info
 
        t2.ApplicationName = appfilepath2
        t2.Parameters = "staff"
        t2.Comment = "Run report from SIMS and upload to Provision Map Writer"
 
        t2.MaxRunTime = New TimeSpan(0, 30, 0)
 
        If gpStaff.Value > 0 Then
            Select Case Me.gpStaff.Value
                'Allow the task to run for no more than 30 minutes.
                Case 1, 4
                    t2.Triggers.Add(New DailyTrigger(18, 38))
                Case 2, 5
                    t2.Triggers.Add(New WeeklyTrigger(10, 30, DaysOfTheWeek.Monday))
                Case 3, 6
                    t2.Triggers.Add(New MonthlyDOWTrigger(10, 30, DaysOfTheWeek.Monday, WhichWeek.FirstWeek))
            End Select
        End If
 
 
        t2.Flags = TaskFlags.RunIfConnectedToInternet
 
        ' Save the changes that have been made.
        t2.Save()
        ' Close the task to release its COM resources.
        t2.Close()
        ' Dispose the ScheduledTasks to release its COM resources.
        st2.Dispose()
    End Sub

Open in new window

0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 125 total points
ID: 22714734
>>1) I need to find a way of adding the current account login password

You won't be able to retreive this information!
0
 

Author Comment

by:Al230762
ID: 22715499
I also think I need to use the Interop.TaskScheduler for Task Scheduler 2.0 in Vista and restrict use of the TaskScheduler 1.0 for XP installations.

Thanks for your help with this so far anyway.
0
 

Author Comment

by:Al230762
ID: 22814234
Thanks for your help with this emoreau. I have got this working now using Task Scheduler 1.0 in Vista. My problem basically I think was that there was no permission to delete the task. If you look at my code there was no account information added at the time the task was created e.g  
 
t.SetAccountInformation(Environment.UserName, vbNullString)

therefore when it came to deleting the task it just woudn't happen. Once this line was added to the task creation code I was subsequently able to delete the task from within the app.
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial will teach you how to censor certain areas of your screen. The example in this video will show a little boy's face being blurred. This will be demonstrated using Adobe Premiere Pro CS6.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question