This article explains how to broadcast messages automatically using a timer without firing any event.

To know how to get started with SignalR, read my article Broadcast Message Using SignalR.

After installing SignalR and hub class, add a timer to the global file.

The following is the hub method:

public void SendMessage(String message)

{

// Call the addMessage methods on all clients

Clients.All.addMessage(message);

}

void Application_Start(object sender, EventArgs e)

{

var aTimer = new System.Timers.Timer(1000);

aTimer.Elapsed += aTimer_Elapsed;

aTimer.Interval = 3000;

aTimer.Enabled = true;

// Code that runs on application startup

// Register the default hubs route: ~/signalr

//RouteTable.Routes.MapHubs();

}

void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

{

var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();

context.Clients.All.addMessage("This message broadcasted on " + DateTime.Now);

}

Client-side code

<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>

<!--Reference the SignalR library. -->

<script src="Scripts/jquery.signalR-1.1.3.js" type="text/javascript"></script>

<!--Reference the autogenerated SignalR hub script. -->

<script src="signalr/hubs"></script>

<script type="text/javascript">

$(function () {

//Proxy created on the fly

var chat = $.connection.chatHub;

// Declare a function on the chat hub so the server can invoke it

chat.client.addMessage = function (message) {

$("#messages").append("<li>" + message + "</li>");

};

$("#broadcast").click(function () {

// call the chat method on the server

chat.server.sendMessage($("#msg").val());

});

$.connection.hub.start();

});

</script>

</head>

<body>

<!--<input type="text" id="msg" />-->

<!-- <input type="button" id="broadcast" value="broadcast" />-->

<ul id="messages" class="round">

</ul>

</body>

Output

SignalR.jpg

As you can see, the message is broadcast every 3 seconds because I have used a timer time interval of 3 seconds.

var aTimer = new System.Timers.Timer(1000);

aTimer.Elapsed += aTimer_Elapsed;

aTimer.Interval = 3000;

aTimer.Enabled = true;