Scala: create a common quartz job class

We use quartz (java API) to schedule tasks. It works well. Now I am trying to generalize some things with this. Quartz api requires a job class as a parameter that extends the Job interface. This makes it impossible to pass arguments through the constructor.

We have a set of tasks that should be done the same way, check if true, and then call an action, for example:

class SimpleJob extends Job {

def execute(context: JobExecutionContext) {
  val check = classOf[SimpleCheck].asInstanceOf[Class[Check]].newInstance()
  val result = check.execute(context.getJobDetail.getJobDataMap)

  if (result.shouldInvokeAction) {
    Action(result).execute
  }
}

Then the quartz task is performed by calling:

newJob(classOf[SimpleJob]).with...

It works.

The goal is to reuse this logic for different types of Question checks. Can I use a system like scala in such a way that I have one typed JobClass that can be reused to execute any Check subclass?

I came up with the following solution:

class GenericJobRule[J <: Check](implicit m: Manifest[J]) extends Job {

  def execute(context: JobExecutionContext) {
    val check = m.erasure.newInstance().asInstanceOf[J]
    val result = check.execute(context.getJobDetail.getJobDataMap)

    if (result.shouldInvokeAction) {
      Action(result).execute
    }
  }
}

:

newJob(classOf[GenericJobRule[PerformanceCheck]])

, , - . ? , ...

,

+5
1

, - . ( ), doCheck ( . here ):

[EDIT]: . .

[EDIT2]: ( ). . . ?

trait GenericJobRule[J <: Check] extends Job {

  val genericCheck: J

  def execute(context: JobExecutionContext) {
    val result = genericCheck.execute(context.getJobDataMap)

    if (result.shouldInvokeAction) {
      Action(result).execute
    }
  }  
}

class JobRule1 extends GenericJobRule[SimpleCheck] {
  override val genericCheck = new SimpleCheck
}

:

newJob(classOf[JobRule1])

[EDIT3]. , GenericJobRule - :

abstract class GenericJobRule[J <: Check] extends Job {

  val genericCheck: J

  def execute(context: JobExecutionContext) {
    val result = genericCheck.execute(context.getJobDataMap)

    if (result.shouldInvokeAction) {
      Action(result).execute
    }
  }  
}

:

val myJobRule = new GenericJobRule[SimpleCheck] { override val genericCheck = new SimpleCheck }
+3

All Articles