Skip to content
Max S edited this page Dec 13, 2016 · 9 revisions

Asynchronous Worker

The cache server has a thread for each slave server connection. There are times when some work needs to be done that would take enough time to slow down the specific slave server thread. For this purpose the cache server has a separate pool of threads that are called asynchronous workers. The core uses them for user registration and user login, for example.

The asynchronous worker API is in the AsyncWorker class and can be called with the AsyncWorker.call() method. Let's take a look at the example (taken from the core and modified):

server.asyncWorker.call('user.register', c.id,
  { id: 10, name: 'Test', password: '123' }, registerWorker);

The first argument is the call name. It should be unique in your project and will be used in log and profiler. The second one is the slave server ID. The third one is an anonymous object with request parameters. The fourth argument is the worker method to run in the asynchronous worker thread.

The worker method is called with three arguments: specific worker thread instance (class AsyncWorkerThread), slave client ID (Int) and parameters given in the API call itself (Dynamic).

Note that each asynchronous worker thread has its own connection to the database. Since the worker method runs in the asynchronous worker thread, it is much better to use the AsyncWorkerThread.query() method to make requests to the database instead of the usual CacheServer.query(). You can call SlaveClient.notify() in the worker method if you need to make a response to the specific slave client, it is thread-safe.

Let's see the contents of worker method:

  function registerWorker(async: AsyncWorkerThread, serverID: Int,
      params: { id: Int, name: String, password: String })
    {
      async.query(
        "INSERT INTO Users (ID, Name, Password) " +
        "VALUES (" + params.id + "," + server.quote(params.name) + "," +
        server.quote(params.password) + ")");

      // do some other work

      // get slave client and notify it
      var gameServer = server.getClient(serverID);
      gameServer.notify({
        _type: 'user.registerComplete',
        id: params.id
        });
    }

Note that in the real case scenario if you want to notify specific client about something, you will have to pass through its client ID or connection ID.

Note: If you intend to make a slow query into the database and then do something with its results, it is more preferable to use the Asynchronous Database Manager API instead since it will not block the thread while waiting for the query results.