Managing threads in Grails Services

后端 未结 2 1705
长情又很酷
长情又很酷 2021-02-08 03:12

So I have a service set up to import a large amount of data from a file the user uploads. I want to the user to be able to continue working on the site while the file is being p

2条回答
  •  遥遥无期
    2021-02-08 03:48

    Another way to do this is to use Spring's @Async annotation.

    Add the following to resources.groovy:

    beans = {
        xmlns task:"http://www.springframework.org/schema/task"
        task.'annotation-driven'('proxy-target-class':true, 'mode':'proxy')
    }
    

    Any service method you now annotate with @Async will run asynchronously, e.g.

    @Async
    def reallyLongRunningProcess() {
        //do some stuff that takes ages
    }
    

    If you only want one thread to run the import at a time, you could do something like this -

    class MyService {
        boolean longProcessRunning = false
    
        @Async
        def reallyLongRunningProcess() {
            if (longProcessRunning) return
    
            try {
                longProcessRunning = true
                //do some stuff that takes ages
            } finally {
                longProcessRunning = false
            }
        }
    }
    

提交回复
热议问题