Click here to Skip to main content
16,018,797 members
Articles / Database Development / SQL Server
Article

SQL Agent: A Job Scheduler Framework

Rate me:
Please Sign up or sign in to vote.
4.88/5 (101 votes)
8 May 2008GPL33 min read 1.4M   13.6K   305   281
An easy-to-use .NET solution for Job Scheduling with pluggable actions that runs on a Windows Service. Back up your SQL Server Express and much more!
Image 1

Introduction

For my last project, I've been using the latest free version of SQL Server, called SQL Server Express Edition, available here. I immediately noticed that the database scheduler was removed since the previous version. I found it really interesting creating my own SQL Agent. In this article, I'll show you how to create a generic scheduler that runs on a Windows Service. The scheduler will be able to accept pluggable actions that we can develop, later implementing a custom interface.

Background

This article is about Jobs Scheduling. You're required to have basic knowledge of how to run and install a Windows Service that uses Microsoft .NET Framework v2.0. A good knowledge of OOP, Interfaces and Reflection is also required in order to understand pluggable actions.

Install It!

The solution provided with this article is composed of four projects:

  • SQLAgent, a Windows Service that wraps the scheduler
  • SQLAgentUI, a Windows Application to control the service from the System Tray
  • EventScheduler, a Class Library containing all the classes composing the Scheduler and the forms to configure it
  • EventSchedulerAction, a Class Library of pluggable actions for the Scheduler jobs

You can install the service using the attached setup or, alternatively, using the command line as shown below:

SQLAgent.exe -i

Run It!

Start the execution of SQLAgentUI and press the button Run beside the label SQL Server Agent. If you do have problems running the system tray application, please go back to the service installation process. Press the button Configure SQL Server Agent to access the configuration page. The following page is shown:

Image 2

You're now ready to configure your jobs!

Using the Code

The core library of the project is EventScheduler. In fact, the event scheduler allows us to schedule our jobs, configure them with a seamless interface and store the settings through an XML file. All these features are one step away from you. We only need to implement the IActionable interface defined by the library. The following is the implementation of the SQL Backup Job.

VB.NET
Imports Microsoft.SqlServer.Management
Imports EventScheduler
Public Class MSSQLBackup
Implements IActionable

#Region "Implements IActionable"
    Protected Shared DefaultParameters() As ActionParameter = _
        {New ActionParameter("Server", _
        ".\SQLExpress"), _
        New ActionParameter("Database", ""), _
        New ActionParameter("Backup Folder", _
        "C:\Backup\")}

    Public ReadOnly Property ActionParameters() As _
        EventScheduler.ActionParameter() _
        Implements IActionable.ActionParameters
        Get
            Return MSSQLBackup.DefaultParameters.Clone
        End Get
    End Property

    Public Sub ActionRun(ByVal s As EventScheduler.Schedule) _
        Implements IActionable.ActionRun
        Dim oParameters() As ActionParameter = s.GetActionParameters
        BackupDatabase(oParameters(0).Value, _
            oParameters(1).Value, _
            oParameters(2).Value)
    End Sub

    Public ReadOnly Property ActionText() As String _
        Implements IActionable.ActionText
        Get
            Return "SQL Server Backup"
        End Get
    End Property
#End Region

#Region "Private Methods"
    Protected Sub BackupDatabase(ByVal ServerName As String, _
        ByVal DatabaseName As String, _
        ByVal BackupFolder As String)
        Try
            Dim srv As New Smo.Server(ServerName)
            Dim bkp As New Smo.Backup
            bkp.Action = Smo.BackupActionType.Database
            bkp.Database = DatabaseName

            Dim filePath As String = BackupFolder
            filePath = System.IO.Path.Combine(BackupFolder, _
                DatabaseName & "-" & Now.Year() & _
                "-" & Now.Month.ToString("00") & _
                "-" & Now.Day.ToString("00") & _
                "-" & Now.Hour.ToString("00") & _
                "-" & Now.Minute.ToString("00") & _
                "-" & Now.Second.ToString("00") & _
                ".bak")

            bkp.Devices.AddDevice(filePath, Smo.DeviceType.File)
            bkp.SqlBackup(srv)

            Catch ex As Exception
        End Try
    End Sub
#End Region

End Class

The following is a screenshot of the Jobs Scheduler settings page:

Image 3

Please note that the Event Scheduler retrieves the data necessary to load the action list using the IActionable interface, as well as the parameters list. The action settings interface will look as follows:

Image 4

The XML file will have the following aspect:

XML
<?xml version="1.0"?>
    <ArrayOfSchedule xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <Schedule xsi:type="DailySchedule" Name="Daily Backup" 
            Active="false" Interval="0">
            <StartTime>2006-08-30T12:45:30.15625+02:00</StartTime>
            <NextInvokeTime>2006-08-31T12:45:30.15625+02:00
            </NextInvokeTime>
            <LastInvokeTime>2006-08-30T12:45:40.84375+02:00
            </LastInvokeTime>
            <Action>0</Action>
            <ActionParameters>
                <ActionParameter>
                    <Name>Server</Name>
                    <Value xsi:type="xsd:string">.\SQLExpress
                    </Value>
                    <Type>NormalActionParameter</Type>
                </ActionParameter>
                <ActionParameter>
                    <Name>Database</Name>
                    <Value xsi:type="xsd:string">MyDatabase</Value>
                    <Type>NormalActionParameter</Type>
                </ActionParameter>
                <ActionParameter>
                    <Name>Backup Folder</Name>
                    <Value xsi:type="xsd:string">C:\Backup\</Value>
                    <Type>NormalActionParameter</Type>
                </ActionParameter>
            </ActionParameters>
            <WeekDays>
                <boolean>false</boolean>
                <boolean>true</boolean>
                <boolean>true</boolean>
                <boolean>true</boolean>
                <boolean>true</boolean>
                <boolean>true</boolean>
                <boolean>false</boolean>
            </WeekDays>
            <BeginValidTime>2006-08-30T00:00:00+02:00</BeginValidTime>
            <EndValidTime>2006-08-30T00:00:00+02:00</EndValidTime>
        </Schedule>
    </ArrayOfSchedule>

Configure It!

SQLAgent and SQLAgentUI are configured to run with the default SQL Server Express instance. Anyway, it's possible to configure it for named instances of SQL Server. The configuration mainly stands on two files:

  • SQLAgent.exe.config
  • SQLAgentUI.exe.config

Extend It!

The pluggable actions for the Event Scheduler actually define a framework for our Windows Services. This makes the application really extensible! I've included in this release:

  • SQL Server Database Backup using SMO
  • SQL Server Database Shrink using SMO
  • Execution of an SQL command
  • Send Email (when used as a PostAction, a [RESULTSET]tag can be included into the message text)
  • Send SMS using Esendex Web Service (when used as a PostAction, a [RESULTSET]tag can be included into the message text)

Please contribute to this project by sending your actions!!!

Final Notes

I hope that you find this article useful. If you find this article stupid, annoying or incorrect, express this fact by rating the article as you see fit. In the end, you're very welcome at any moment to freely contribute to this project by suggesting improvements, or by submitting code or other materials.

Credits

  • Thanks to Gonzalo Brusella for the reflection implementation
  • Thanks to Lukasz Swiatkowski for the cool glass button
  • Thanks to Nick Wälti for his beautiful gradient panel
  • Thanks to Sriram Chitturi for his article on events scheduling

References

History

  • 30th August, 2006 – First submission
  • 6th April 2007, – Project updated
  • 10th August, 2007 – Project updated
  • 4th September, 2007 - Project updated
  • 18th September, 2007 - Project updated
  • 6th May, 2008 - Project updated

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)


Written By
Software Developer (Senior)
Italy Italy
I am 40 years old and I've been working with C++, Visual Basic .NET, C# and ASP.NET. I have a large experience in Industrial Automation solutions, but I've worked also as Web developer and DBA. I like to share knowledge and projects with other people.

Comments and Discussions

 
AnswerRe: smo - job scheduling Pin
Danilo Corallo12-Apr-07 2:33
Danilo Corallo12-Apr-07 2:33 
AnswerRe: smo - job scheduling Pin
dany0w12-Apr-07 10:48
dany0w12-Apr-07 10:48 
General6 April Update Pin
Tailslide10-Apr-07 12:20
Tailslide10-Apr-07 12:20 
GeneralRe: 6 April Update Pin
Tailslide19-Jul-07 12:22
Tailslide19-Jul-07 12:22 
GeneralMissing Setup Project Pin
lberman6-Apr-07 3:45
lberman6-Apr-07 3:45 
AnswerRe: Missing Setup Project Pin
Danilo Corallo6-Apr-07 4:40
Danilo Corallo6-Apr-07 4:40 
GeneralVista - Interactive Services Dialog Detection Pin
Tailslide8-Mar-07 9:39
Tailslide8-Mar-07 9:39 
GeneralRe: Vista - Interactive Services Dialog Detection Pin
Tailslide10-Apr-07 12:16
Tailslide10-Apr-07 12:16 
If you display the UI from the client instead of the service this fixes it.

However, then you need to change the client to restart the service after changes to the schedule to pick up the new xml. Also, when someone manually executes a schedule item you need to bundle up the schedule actions into a remote IPC call and send it to the service since the client doesn't seem to have permission to execute a SQL backup but the service does.

Ideally, you could incorporate all the schedule updates into remote calls as well then you wouldn't have to resort to restarting the service.

GeneralUsing this with SQL Server 2005 Pin
AlexEvans7-Feb-07 11:36
AlexEvans7-Feb-07 11:36 
GeneralRe: Using this with SQL Server 2005 Pin
Danilo Corallo21-Feb-07 2:47
Danilo Corallo21-Feb-07 2:47 
NewsRe: Using this with SQL Server 2005 Pin
Danilo Corallo6-Apr-07 4:58
Danilo Corallo6-Apr-07 4:58 
QuestionAccessing scheduler data remotely Pin
BraveShogun14-Jan-07 21:20
BraveShogun14-Jan-07 21:20 
AnswerRe: Accessing scheduler data remotely Pin
Danilo Corallo21-Feb-07 2:53
Danilo Corallo21-Feb-07 2:53 
QuestionSQLAgentUI does not start Pin
javalier24-Dec-06 18:55
javalier24-Dec-06 18:55 
AnswerRe: SQLAgentUI does not start Pin
Danilo Corallo6-Jan-07 3:12
Danilo Corallo6-Jan-07 3:12 
GeneralC# version of this Pin
BraveShogun18-Dec-06 23:34
BraveShogun18-Dec-06 23:34 
GeneralSchedule Dialog Wont Show across Remote Desktop Sessions Pin
DotCom7215-Dec-06 12:16
DotCom7215-Dec-06 12:16 
GeneralRe: Schedule Dialog Wont Show across Remote Desktop Sessions Pin
Danilo Corallo6-Jan-07 3:18
Danilo Corallo6-Jan-07 3:18 
GeneralRe: Schedule Dialog Wont Show across Remote Desktop Sessions Pin
ohanus29-May-07 4:10
ohanus29-May-07 4:10 
GeneralRe: Schedule Dialog Wont Show across Remote Desktop Sessions Pin
Tailslide19-Jul-07 11:04
Tailslide19-Jul-07 11:04 
Generalmesage eror Cannot open MSSQL$SQLEXPRESS Pin
spawn_ae14-Dec-06 7:20
spawn_ae14-Dec-06 7:20 
GeneralRe: mesage eror Cannot open MSSQL$SQLEXPRESS Pin
DotCom7215-Dec-06 12:19
DotCom7215-Dec-06 12:19 
AnswerRe: mesage eror Cannot open MSSQL$SQLEXPRESS Pin
Danilo Corallo6-Apr-07 4:57
Danilo Corallo6-Apr-07 4:57 
Questionvb.net 1.1 version Pin
drfunky29-Nov-06 4:49
drfunky29-Nov-06 4:49 
AnswerRe: vb.net 1.1 version Pin
Danilo Corallo30-Nov-06 4:37
Danilo Corallo30-Nov-06 4:37 

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

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