My question is pretty simple: how is event-driven programming actually achieved?
To elaborate: I have a Rails application, every time a user makes a change on the website, the model writes that "change" to a text file (as JSON.)
What I'd like to do is hook an IRC bot to that "event." (the creation/modification of the text file.)
How is this done in general? It seems like it'd basically be an infinite loop. In pseudocode:
while (I'm Listening)
do
if (output.txt Is changed)
process("output.txt")
If this is how event-driven programming is achieved - how does it avoid locking up the CPU? As infinite loops have a tendency to do?
Edit- The IRC server/bot are hosted on a locally maintained box. The Rails application is hosted on a shared server. As of now, the only way I know for my IRC bot to communicate with the Rails app is via an HTTP request to the server (or something similar.) As I stated though, this question is really more general, as I'd like to garner a knowledge of event-driven programming in general.
I apologize if this question is impossibly simple, but my understanding of event driven programming consists of attaching pre-made event handlers to objects with jQuery; which really doesn't help when attaching an IRC bot [written in Ruby] to file I/O.
Thanks, Robbie
More often, its like this:
while (I'm Waiting to be notified)
do
if (output.txt Is changed)
process("output.txt")
There are ways in the OS (any OS) to wait to be notified without taking CPU time (such as a condition variable.) No event driven loop is sitting there spinning waiting for an event.
A basic model that I am familiar with is done by creating a class which exposes events which can be subscribed to. This can be as simple as a collection of methods.
class Foo
attr_accessor :event #obviously not the right way to do it, but it will suffice
def initialize
@event = []
end
private
def fire_event
@event.each { |sub| sub.call }
end
end
Now clients of this class can pass in a method that they wish to be executed when the event is fired.
f = Foo.new
f.event << lambda { puts 'event was fired' }
When the Foo class calls the fire_event method each procedure in the collection of procedures will be executed. There is no loop constantly checking some condition. When the condition arises, the firing method is called and the procedures are executed.
On a side note the example above is just that; an example. A real world event architecture would be more robust, but the will be similar. This may not even apply to your actual situation, but I am not a web guy and I don't know RoR and JSON and all those other fancy keywords, so I went high level. Hopefully it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With