service-task

Service task

File: ./service-host.js


const Path = require('path')
const debug = require('debug')('test.server-db')
const Dataparty = require('../src')

class ExampleTaskService extends Dataparty.IService {
  constructor(opts){
    super(opts)

    this.addTask(Path.join(__dirname,'./tasks/status-display.js'))
  }

}

async function main(){

  
  const service = new ExampleTaskService({ name: '@dataparty/task-example', version: '0.0.1' })

  const build = await service.compile(Path.join(__dirname,'/dataparty'), true)

  debug('built', Object.keys(build))

  const path = '/data/datparty/srv-party'

  let party = new Dataparty.TingoParty({
    path,
    model: build,
    config: new Dataparty.Config.JsonFileConfig({basePath: '/data/datparty/'})
  })


  const runner = new Dataparty.ServiceRunnerNode({
    party, service,
    sendFullErrors: false,
    useNative: true
  })
  
  const host = new Dataparty.ServiceHost({
    runner,
    trust_proxy: true,
    wsEnabled: true,
    listenUri: 'http://localhost:8080'
  })

  await party.start()
  await runner.start()
  await host.start()

  console.log('started')
  
}



main().catch(err=>{
  console.error(err)
})

File: ./tasks/status-display.js


  const debug = require('debug')('dataparty.task.status-update')

  const ITask = require('@dataparty/api').Service.ITask
  
  class StatusDisplayTask extends ITask {
  
    constructor(options){
      super({
        name: StatusDisplayTask.name,
        background: StatusDisplayTask.Config.background,
        ...options
      })
  
      debug('new')
  
      this.duration = 5000
      this.timeout = null
    }
  
    static get Config(){
      return {
        background: true,
        autostart: true
      }
    }
   
    async exec(){
  
      this.setTimer()
  
      return this.detach()
    }
  
    setTimer(){
      this.timeout = setTimeout(this.onTimeout.bind(this), this.duration)
    }
   
    onTimeout(){
      this.timeout = null
      
      debug('sleep complete')
      console.log('task sleep complete, setting new timer')
      
      this.context.serviceRunner.taskRunner.printTaskLists()
      
      this.setTimer()
    }
   
    stop(){
      if(this.timeout !== null){
        clearTimeout(this.timeout)
        this.timeout = null
      }
    }
  
    static get Name(){
      return 'status-display'
    }
  
    static get Description(){
      return 'Status Display'
    }
  }
  
  module.exports = StatusDisplayTask