Skip to content

Instantly share code, notes, and snippets.

@phyous
Last active December 19, 2015 17:29
Show Gist options
  • Save phyous/5991288 to your computer and use it in GitHub Desktop.
Save phyous/5991288 to your computer and use it in GitHub Desktop.
How to schedule background tasks in Play with Akka. Example below sends an email every 5 seconds
# This is the main configuration file for the application.
# ~~~~~
# Secret key
# ~~~~~
# The secret key is used to secure cryptographics functions.
# If you deploy your application to several instances be sure to use the same key!
application.secret="foobar"
# The application languages
# ~~~~~
application.langs="en"
# Global object class
# ~~~~~
# Define the Global object class for this application.
# Default to Global in the root package.
application.global=Global
# Logger
# ~~~~~
# You can also configure logback (http://logback.qos.ch/), by providing a logger.xml file in the conf directory .
# Root logger:
logger.root=ERROR
# Logger used by the framework:
logger.play=INFO
# Logger provided to your application:
logger.application=DEBUG
# Akka
# ~~~~~
akka.default-dispatcher.core-pool-size-max = 64
akka.debug.receive = on
import sbt._
import Keys._
import play.Project._
object ApplicationBuild extends Build {
val appName = "chain-mail"
val appVersion = "1.0-SNAPSHOT"
val appDependencies = Seq(
"org.codemonkey.simplejavamail" % "simple-java-mail" % "2.1"
)
val main = play.Project(appName, appVersion, appDependencies).settings(
// Add your own project settings here
)
}
import javax.mail.Message.RecipientType
import org.codemonkey.simplejavamail.{TransportStrategy, Mailer, Email}
import play.api._
import play.api.Play.current
import play.api.libs.concurrent._
import play.api.libs.concurrent.Execution.Implicits._
import scala.concurrent.duration._
object Global extends GlobalSettings {
override def onStart(app: Application) {
Logger.info("Application has started")
startAwesomeBackgroundTask
}
override def onStop(app: Application) {
Logger.info("Application shutdown...")
}
def startAwesomeBackgroundTask = {
Akka.system.scheduler.schedule(0 seconds, 5 seconds) {
val email = new Email()
email.setFromAddress("FooBar Daemon", "[email protected]");
email.setSubject("Alert!");
email.addRecipient("Foo Bar", "[email protected]", RecipientType.TO);
email.setTextHTML("<img src='cid:wink1'><b>There was an alert!</b><img src='cid:wink2'>");
new Mailer("smtp.gmail.com", 465, "[email protected]", "password", TransportStrategy.SMTP_SSL).sendMail(email);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment