Last active
April 5, 2017 11:48
-
-
Save fushnisoft/83e3d94576805ce81179f047b27b76c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Hangfire; | |
using Microsoft.Owin; | |
using Microsoft.Owin.Hosting; | |
using Owin; | |
using Serilog; | |
using System; | |
using System.Data.SqlClient; | |
using Topshelf; | |
[assembly: OwinStartup(typeof(MyScheduler.Startup))] | |
namespace MyScheduler | |
{ | |
internal class Startup | |
{ | |
public void Configuration(IAppBuilder app) | |
{ | |
app.UseHangfireDashboard(); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Log.Logger = new LoggerConfiguration() | |
.MinimumLevel.Debug() | |
.WriteTo.RollingFile(AppDomain.CurrentDomain.BaseDirectory + "logs\\MyScheduler-{Date}.log") | |
.WriteTo.ColoredConsole() | |
.CreateLogger(); | |
Log.Information("Hello, world!"); | |
HostFactory.Run(x => | |
{ | |
x.Service<JobHost>(s => | |
{ | |
s.ConstructUsing(name => new JobHost()); | |
s.WhenStarted(tc => tc.Start()); | |
s.WhenStopped(tc => tc.Stop()); | |
}); | |
x.RunAsNetworkService(); | |
x.SetServiceName("MyScheduler"); | |
x.SetDisplayName("MyScheduler"); | |
x.SetDescription("Sample MyScheduler Host"); | |
x.UseSerilog(); | |
// x.SetInstanceName("MyService"); <-- this should be handy for multiple Trips instances! | |
}); | |
} | |
} | |
public class JobHost | |
{ | |
private BackgroundJobServer _server; | |
private string _connectionString = @"Server=myserver;Database=Hangfire;User Id=username;Password=****;"; | |
private IDisposable app; | |
public JobHost() | |
{ | |
GlobalConfiguration.Configuration.UseSqlServerStorage(_connectionString); | |
RecurringJob.AddOrUpdate(() => DoStuff(), Cron.Minutely); | |
} | |
public void DoStuff() | |
{ | |
Log.Information("It is {0} and all is well", DateTime.Now); | |
GetServerDateTime(); | |
} | |
public void Start() { | |
app = WebApp.Start<Startup>("http://localhost:5000"); | |
_server = new BackgroundJobServer(); | |
} | |
public void Stop() { | |
app.Dispose(); | |
_server.Dispose(); | |
} | |
public void GetServerDateTime() | |
{ | |
string queryString = "SELECT GetDate() as CurrentDateTime;"; | |
using (SqlConnection connection = new SqlConnection(_connectionString)) | |
{ | |
SqlCommand command = new SqlCommand(queryString, connection); | |
connection.Open(); | |
SqlDataReader reader = command.ExecuteReader(); | |
try | |
{ | |
while (reader.Read()) | |
{ | |
Log.Information("SQL DateTime: " + reader["CurrentDateTime"]); | |
} | |
} | |
finally | |
{ | |
// Always call Close when done reading. | |
reader.Close(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment